一个完整的括号字符串定义规则如下:
1、空字符串是完整的。
2、如果s是完整的字符串,那么(s)也是完整的。
3、如果s和t是完整的字符串,将它们连接起来形成的st也是完整的。
例如,"(()())", ""和"(())()"是完整的括号字符串,"())(", "()(" 和 ")"是不完整的括号字符串。
1、空字符串是完整的。
2、如果s是完整的字符串,那么(s)也是完整的。
3、如果s和t是完整的字符串,将它们连接起来形成的st也是完整的。
例如,"(()())", ""和"(())()"是完整的括号字符串,"())(", "()(" 和 ")"是不完整的括号字符串。
牛牛有一个括号字符串s,现在需要在其中任意位置尽量少地添加括号,将其转化为一个完整的括号字符串。请问牛牛至少需要添加多少个括号。
#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
int main()
{
int max_deep = 0;
stack<char> count_left , count_right ;
char s;
while((s = getchar()) != '\n'){
if(s == '('){
count_left.push('(');
}else{
if(count_left.empty()){
count_right.push(')');
}
else{
count_left.pop();
}
}
}
cout << count_left.size() + count_right.size() << endl;
return 0;
}
上面这个是要求稍微有难度的问题。有的类似题目比较简单:
要求是:"(()())", ""和"(())()"是完整的括号字符串,不会出现非法字符串或者括号不匹配的问题。
如果这样的话代码就仅仅小小的改动就可:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int max_deep = 0;
int count_sign = 0;
char s;
while ((s = getchar()) != '\n'){
if (s == '('){
count_sign++;
if (max_deep < count_sign){
max_deep = count_sign;
}
}
else{
count_sign--;
}
}
cout << max_deep << endl;
return 0;
}