给定一个仅由字符‘1’、’2′和‘3’组成的数字字符串S ,任务是用开括号( ‘(‘ ) 或闭括号 ( ‘)’ )替换字符,使得新形成的字符串成为平衡括号序列。
注意:所有出现的字符必须替换为相同的括号。
例子:
Input: S = “1123”
Output: Yes, (())
Explanation: Replacing occurrences of character ‘1’ with ‘(‘, ‘2’ with ‘)’ and ‘3’ with ‘)’. Therefore, the obtained bracket sequence is “(())”, which is balanced.
Input: S = “1121”
Output: No
方法:根据以下观察可以解决给定的问题:
- 对于平衡支架序列,有必要为第一和最后一个字符是打开和关闭分别括号。因此,第一个和最后一个字符应该不同。
- 如果第一和字符串的最后一个字符是相同的,那么就不可能获得平衡的支架序列。
- 如果字符串的第一个和最后一个字符是不同的,那么它们被打开和关闭括号分别替换。第三个字符是通过打开或关闭托架任一替换。
- 检查剩余的第三个字符的两种替换方式。
- 如果剩下的第三个字符的两个替换都不能构成平衡括号序列,那么就不可能构成平衡括号序列。
请按照以下步骤解决给定的问题:
- 检查字符串S的第一个和最后一个字符是否相等。如果发现为真,则打印“否”并返回。
- 初始化两个变量,比如cntforOpen和cntforClose ,以存储开括号和闭括号的计数。
- 遍历字符串中的字符,然后执行以下操作:
- 如果当前字符与字符串的第一个字符相同,则增加cntforOpen。
- 如果当前字符与字符串的最后一个字符相同,则递减cntforOpen。
- 对于剩余的第三个字符,增加cntforOpen ,即用‘(‘替换该字符。
- 如果在任何时刻,发现cntforOpen为负,则无法获得平衡的括号序列。
- 同样,使用cntforClose变量进行检查,即将第三个字符替换为‘)’ 。
- 如果以上两种方法都没有生成平衡括号序列,则打印“No” 。否则,打印“是”。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if the given
// string can be converted to a
// balanced bracket sequence or not
void balBracketSequence(string str)
{
int n = str.size();
// Check if the first and
// last characters are equal
if (str[0]
== str[n - 1])
{
cout << "No" << endl;
}
else {
// Initialize two variables to store
// the count of open and closed brackets
int cntForOpen = 0, cntForClose = 0;
int check = 1;
for (int i = 0; i < n; i++) {
// If the current character is
// same as the first character
if (str[i] == str[0])
cntForOpen++;
// If the current character is
// same as the last character
else if (str[i] == str[n - 1])
cntForOpen--;
else
cntForOpen++;
// If count of open brackets
// becomes less than 0
if (cntForOpen < 0) {
check = 0;
break;
}
}
if (check && cntForOpen == 0) {
cout << "Yes, ";
// Print the new string
for (int i = 0; i < n; i++) {
if (str[i] == str[n - 1])
cout << ')';
else
cout << '(';
}
return;
}
else {
for (int i = 0; i < n; i++) {
// If the current character is
// same as the first character
if (str[i] == str[0])
cntForClose++;
else
cntForClose--;
// If bracket sequence
// is not balanced
if (cntForClose
< 0) {
check = 0;
break;
}
}
// Check for unbalanced
// bracket sequence
if (check
&& cntForClose
== 0) {
cout << "Yes, ";
// Print the sequence
for (int i = 0; i < n;
i++) {
if (str[i] == str[0])
cout << '(';
else
cout << ')';
}
return;
}
}
cout << "No";
}
}
// Driver Code
int main()
{
// Given Input
string str = "123122";
// Function Call
balBracketSequence(str);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to check if the given
// string can be converted to a
// balanced bracket sequence or not
static void balBracketSequence(String str)
{
int n = str.length();
// Check if the first and
// last characters are equal
if (str.charAt(0)
== str.charAt(n - 1))
{
System.out.println("No");
}
else {
// Initialize two variables to store
// the count of open and closed brackets
int cntForOpen = 0, cntForClose = 0;
int check = 1;
for (int i = 0; i < n; i++) {
// If the current character is
// same as the first character
if (str.charAt(i) == str.charAt(0))
cntForOpen++;
// If the current character is
// same as the last character
else if (str.charAt(i) == str.charAt(n - 1))
cntForOpen -= 1;
else
cntForOpen += 1;
// If count of open brackets
// becomes less than 0
if (cntForOpen < 0) {
check = 0;
break;
}
}
if (check != 0 && cntForOpen == 0) {
System.out.print("Yes, ");
// Print the new string
for (int i = 0; i < n; i++) {
if (str.charAt(i) == str.charAt(n - 1))
System.out.print(')');
else
System.out.print('(');
}
return;
}
else {
for (int i = 0; i < n; i++) {
// If the current character is
// same as the first character
if (str.charAt(i) == str.charAt(0))
cntForClose++;
else
cntForClose--;
// If bracket sequence
// is not balanced
if (cntForClose
< 0) {
check = 0;
break;
}
}
// Check for unbalanced
// bracket sequence
if (check != 0
&& cntForClose
== 0) {
System.out.print("Yes, ");
// Print the sequence
for (int i = 0; i < n;
i++) {
if (str.charAt(i) == str.charAt(0))
System.out.print('(');
else
System.out.print(')');
}
return;
}
}
System.out.print("No");
}
}
// Driver Code
public static void main(String args[])
{
// Given Input
String str = "123122";
// Function Call
balBracketSequence(str);
}
}
// This code is contributed by ipg2016107.
Python3
# Python program for the above approach;
# Function to check if the given
# string can be converted to a
# balanced bracket sequence or not
def balBracketSequence(str):
n = len(str)
# Check if the first and
# last characters are equal
if (str[0] == str[n - 1]):
print("No", end="")
else:
# Initialize two variables to store
# the count of open and closed brackets
cntForOpen = 0
cntForClose = 0
check = 1
for i in range(n):
# If the current character is
# same as the first character
if (str[i] == str[0]):
cntForOpen += 1
# If the current character is
# same as the last character
elif str[i] == str[n - 1] :
cntForOpen -= 1
else:
cntForOpen += 1
# If count of open brackets
# becomes less than 0
if (cntForOpen < 0):
check = 0
break
if (check and cntForOpen == 0):
print("Yes, ", end="")
# Prlet the new string
for i in range(n):
if (str[i] == str[n - 1]):
print(')', end="")
else:
print('(', end="")
return
else:
for i in range(n):
# If the current character is
# same as the first character
if (str[i] == str[0]):
cntForClose += 1
else:
cntForClose -= 1
# If bracket sequence
# is not balanced
if (cntForClose < 0):
check = 0
break
# Check for unbalanced
# bracket sequence
if (check and cntForClose == 0):
print("Yes, ", end="")
# Prlet the sequence
for i in range(n):
if (str[i] == str[0]):
print('(', end="")
else:
print(')', end="")
return
print("NO", end="")
# Driver Code
# Given Input
str = "123122"
# Function Call
balBracketSequence(str)
# This code is contributed by gfgking
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to check if the given
// string can be converted to a
// balanced bracket sequence or not
static void balBracketSequence(string str)
{
int n = str.Length;
// Check if the first and
// last characters are equal
if (str[0] == str[n - 1])
{
Console.Write("No");
}
else
{
// Initialize two variables to store
// the count of open and closed brackets
int cntForOpen = 0, cntForClose = 0;
int check = 1;
for(int i = 0; i < n; i++)
{
// If the current character is
// same as the first character
if (str[i] == str[0])
cntForOpen++;
// If the current character is
// same as the last character
else if (str[i] == str[n - 1])
cntForOpen--;
else
cntForOpen++;
// If count of open brackets
// becomes less than 0
if (cntForOpen < 0)
{
check = 0;
break;
}
}
if (check != 0 && cntForOpen == 0)
{
Console.Write("Yes, ");
// Print the new string
for(int i = 0; i < n; i++)
{
if (str[i] == str[n - 1])
Console.Write(')');
else
Console.Write('(');
}
return;
}
else
{
for(int i = 0; i < n; i++)
{
// If the current character is
// same as the first character
if (str[i] == str[0])
cntForClose++;
else
cntForClose--;
// If bracket sequence
// is not balanced
if (cntForClose < 0)
{
check = 0;
break;
}
}
// Check for unbalanced
// bracket sequence
if (check != 0 && cntForClose == 0)
{
Console.Write("Yes, ");
// Print the sequence
for(int i = 0; i < n; i++)
{
if (str[i] == str[0])
Console.Write('(');
else
Console.Write(')');
}
return;
}
}
Console.Write("No");
}
}
// Driver Code
public static void Main()
{
// Given Input
string str = "123122";
// Function Call
balBracketSequence(str);
}
}
// This code is contributed by sanjoy_62
Javascript
输出:
Yes, ()(())
时间复杂度: O(N)
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。