字符串是字符数组。在这个问题中,我们给了一个带有开括号和闭括号的字符串。我们将通过从字符串中删除多余的括号来平衡该字符串。
让我们举个例子
Input : “)Tutor)ials(p(oin)t(...)” Output : “Tutorials(p(oin)t(...))”
为了解决这个问题,我们将遍历字符串并检查是否有匹配的括号。对于不匹配的括号,请消除右括号。
Step 1 : Traverse the string from left to right. Step 2 : For opening bracket ‘(’ , print it and increase the count. Step 3 : For occurence of closing bracket ‘)’ , print it only if count is greater than 0 and decrease the count. Step 4 : Print all characters other than brackets are to be printed in the array. Step 5 : In the last add closing brackets ‘)’ , to make the count 0 by decrementing count with every bracket.
#include<iostream>
#include<string.h>
using namespace std;
void balancedbrackets(string str){
int count = 0, i;
int n = str.length();
for (i = 0; i < n; i++) {
if (str[i] == '(') {
cout << str[i];
count++;
}
else if (str[i] == ')' && count != 0) {
cout << str[i];
count--;
}
else if (str[i] != ')')
cout << str[i];
}
if (count != 0)
for (i = 0; i < count; i++)
cout << ")";
}
int main() {
string str = ")Tutor)ials(p(oin)t(...)";
cout<<"Original string : "<<str;
cout<<"\nBalanced string : ";
balancedbrackets(str);
return 0;
}输出结果
Original string : )Tutor)ials(p(oin)t(...) Balanced string : Tutorials(p(oin)t(...))