一个完整的括号字符串定义规则如下:
1、空字符串是完整的。
2、如果s是完整的字符串,那么(s)也是完整的。
3、如果s和t是完整的字符串,将它们连接起来形成的st也是完整的。
例如,"(()())", ""和"(())()"是完整的括号字符串,"())(", "()(" 和 ")"是不完整的括号字符串。
牛牛有一个括号字符串s,现在需要在其中任意位置尽量少地添加括号,将其转化为一个完整的括号字符串。请问牛牛至少需要添加多少个括号。
输入包括一行,一个括号序列s,序列长度length(1 ≤ length ≤ 50). s中每个字符都是左括号或者右括号,即'('或者')'.
输出一个整数,表示最少需要添加的括号数
(()(()
2
#include <iostream> #include <string> #include <stack> using namespace std; int main() { string S; cin >> S; int nmistakes = 0; stack<char> stk; for (auto c : S) { if (c == '(') { stk.push(c); } else { if (stk.empty()) nmistakes++; else stk.pop(); } } nmistakes += stk.size(); cout << nmistakes << endl; }
//先把string里所有合法的括号对都去掉,剩下的string length就是我们需要加的括号数量了#include <iostream>#include <string>#include <algorithm>using namespace std;int findIndex(string s){for(int i=0; i<s.length(); i++){if(s[i]=='('&&s[i+1]==')'){return i;}}return -1;}int numBracket(string s){int len = s.length();int temp;while(true){temp = findIndex(s);if(temp==-1) break;while(temp>=0&&s[temp]=='('&&s[temp+1]==')'){s.erase(temp,2);temp--;}}returns.length();}int main(){string s;cin >> s;cout << numBracket(s) << endl;return 0;}