Leyni得到了一个由"(“和”)“组成的字符串,比如”(())()","()","(()(()))“是括号匹配的,而”)(","(()","(()))("是括号不匹配的。 为了让这个字符串括号匹配,Leyni可以去除某些括号。 他想知道,他能得到的最长的括号匹配的字符串有多长?
Input
本题有多组测试数据,输入的第一行是一个整数T代表着测试数据的数量,接下来是T组测试数据。 对于每组测试数据: 第1行 包含一个由"(“和”)"组成的非空字符串,字符串的长度不超过106。
Output
对于每组测试数据: 第1行 输出Leyni能得到的最长的括号匹配的字符串。
Sample Input
2
(()))(
((()())
Sample Output
4
6
注意方法:
读入一个字符,如果是“(”左括号,则入栈;如果是“)”右括号,则与栈(不为空)顶元素相匹配。每匹配一次,累计数量加2。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
int main()
{
stack<char>s;
char c;
int t;
scanf("%d%*c",&t); //注意消除换行符对下面的运算带来的影响
while(t--)
{
int cnt=0;
while(!s.empty())
s.pop();
while(scanf("%c",&c)!=EOF)
{
if(c=='\n')
break;
else if(c=='(')
s.push(c);
else if(c==')'&&!s.empty())
{
s.pop();
cnt++;
}
}
cnt=cnt*2;
cout<<cnt<<endl;
}
return 0;
}
稍微有点不同的另一写法
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
int n;
string s;
stack <int> q;
int main()
{
cin>>n;
while(n--)
{
while(!q.empty())
{
q.pop();
}
cin>>s;
int ans=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(')
q.push(1);
if(s[i]==')')
{
if(q.empty())
continue;
else
{
q.pop();
ans+=2;
}
}
}
cout<<ans<<endl;
}
return 0;
}