括号配对问题
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
现在,有一行括号序列,请你检查这行括号是否配对。
-
输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No 样例输入
-
3 [(]) (]) ([[]()])
样例输出
-
No No Yes
来源
- 网络 上传者
题解:栈
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; #include<stack> char s[10000]; int pan(char c1,char c2){ if(c1=='['){ if(c2==']') return 1; else return 0; } else if(c1=='('){ if(c2==')') return 1; else return 0; } else return 0; } int main(){ int t; scanf("%d",&t); stack<char>S; while(t--){ while(!S.empty()) S.pop(); scanf("%s",s); int l=strlen(s); for(int i=0;i<l;i++){ if(S.empty()||pan(S.top(),s[i])==0)//栈空或者与栈顶配对 S.push(s[i]); else S.pop(); } if(S.empty()) printf("Yes"); else printf("No"); if(t!=0) printf("\n"); } }