括号匹配 hrbust
用栈将不能匹配的存起来:
括号匹配 | |||||
|
|||||
Description | |||||
Leyni得到了一个由"("和")"组成的字符串,比如"(())()","()","(()(()))"是括号匹配的,而")(","(()","(()))("是括号不匹配的。 为了让这个字符串括号匹配,Leyni可以去除某些括号。 他想知道,他能得到的最长的括号匹配的字符串有多长? |
|||||
Input | |||||
本题有多组测试数据,输入的第一行是一个整数T代表着测试数据的数量,接下来是T组测试数据。 对于每组测试数据: 第1行 包含一个由"("和")"组成的非空字符串,字符串的长度不超过106。 |
|||||
Output | |||||
对于每组测试数据: 第1行 输出Leyni能得到的最长的括号匹配的字符串。 |
|||||
Sample Input | |||||
2 (()))( ((()()) |
|||||
Sample Output | |||||
4 6 1 #include<stdio.h> 2 #include<string.h> 3 #define MAX 1000010 4 char queue[MAX],s[MAX]; 5 int main() 6 { 7 int t,len,i,rear; 8 scanf("%d",&t); 9 while(t--) 10 { 11 scanf("%s",s); 12 len=strlen(s); 13 rear=0; 14 for(i=0;i<len;i++) 15 { 16 if(rear==0) 17 queue[++rear]=s[i]; 18 else if(queue[rear]=='('&&s[i]==')') 19 rear--; 20 else queue[++rear]=s[i]; 21 } 22 printf("%d\n",len-rear); 23 } 24 return 0; 25 }
|