题目链接:http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1271
Description
Let us define a regular brackets sequence in the following way:
1. Empty sequence is a regular sequence.
2. If S is a regular sequence, then (S) is a regular sequence.
3. If A and B are regular sequences, then AB is a regular sequence.
For example, these sequences of characters are regular brackets sequences: (), (()), ()(), ()(()), ((())())().
And all the following character sequences are not: (, ), ((), ()), ())(, (()(, ()))().
A sequence of characters '(' and ')' is given. You can insert only one '(' or ')' into the left of the sequence, the right of the sequence, or the place between any two adjacent characters, to try changing this sequence to a regular brackets sequence.
Input
The first line has a integer T (1 <= T <= 200), means there are T test cases in total.
For each test case, there is a sequence of characters '(' and ')' in one line. The length of the sequence is in range [1, 105].
Output
For each test case, print how many places there are, into which you insert a '(' or ')', can change the sequence to a regular brackets sequence.
What's more, you can assume there has at least one such place.
Sample Input
4
)
())
(()(())
((())())(()
Sample Output
1
3
7
3
HINT
Source
题意:
问能有多少种方法,使字符串的括号完整!
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int num[100017];
char s[100017];
int main()
{
int t;
int n;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
int len = strlen(s);
int tt = 0;
for(int i = 0; i < len; i++)
{
if(s[i]=='(')
num[i] = 1;
if(s[i]==')')
num[i] = -1;
tt+=num[i];
}
int sum = 0;
int ans = 0;
if(tt == 1)//缺右括号
{
for(int i = 0; i < len; i++)
{
sum+=num[i];
//printf("sum:%d\n",sum);
if(sum > 0)
ans++;
else if(sum == 0)
ans=0;
}
}
else if(tt == -1)//缺左括号
{
for(int i = len-1; i >= 0; i--)
{
sum+=num[i];
//printf("sum:%d\n",sum);
if(sum < 0)
ans++;
else if(sum == 0)
ans=0;
}
}
printf("%d\n",ans);
}
return 0;
}