题目描述
一个完整的括号字符串定义规则如下:
1、空字符串是完整的。
2、如果s是完整的字符串,那么(s)也是完整的。
3、如果s和t是完整的字符串,将它们连接起来形成的st也是完整的。
例如,"(()())", ""和"(())()"是完整的括号字符串,"())(", "()(" 和 ")"是不完整的括号字符串。
牛牛有一个括号字符串s,现在需要在其中任意位置尽量少地添加括号,将其转化为一个完整的括号字符串。请问牛牛至少需要添加多少个括号。
输入描述:
输入包括一行,一个括号序列s,序列长度length(1 ≤ length ≤ 50).
s中每个字符都是左括号或者右括号,即'('或者')'.
输出描述:
输出一个整数,表示最少需要添加的括号数
示例1
输入
(()(()
输出
2
这道题目可以用栈模拟,也可以简化版,直接运用括号序列的特点,空间复杂度为O(1)
括号序列有如下特点,如果将(看成是加一,)看成是-1, 那么再这个过程种,状态必须恒大于0,且最后等于0,这样就是匹配的,否则就是不匹配的。
有如下代码
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
string str;
cin>>str;
int res=0;
int temp = 0;
for(auto c:str){
if(c=='(')
temp+=1;
else if(c==')')
temp+=-1;
if(temp<0){
temp=0;
res++;
}
}
cout<<res+temp<<endl;
}
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
string str;
cin>>str;
stack<char> st;
int res=0;
for(auto c:str){
if(c=='(') st.push(c);
else{
if(st.empty())
res++; // 填一个右括号
else
st.pop();
}
}
cout<<res+st.size()<<endl;
}