移除多余括号后平衡 C++ 中的字符串
字符串是字符数组。在这个问题中,我们给定了一个包含开括号和闭括号的字符串。我们将通过从字符串中移除多余的括号来平衡该字符串。
我们举个例子,
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(...))
广告