括号配对问题
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
现在,有一行括号序列,请你检查这行括号是否配对。
-
输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No 样例输入
-
3 [(]) (]) ([[]()])
样例输出
-
No No
Yes
-
-
栈的应用
-
-
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <algorithm> using namespace std; char s[10055]; char a[10005]; int fun(char x,char y )//判断栈顶元素与将要入栈的元素是否可以配对。 { if(x=='('&&y==')') return 1; else if(x=='['&&y==']') return 1; else return 0; } int main() { int n; scanf("%d",&n); while(n--) { scanf("%s",s); int top=-1; int d=strlen(s); if(d%2!=0) printf("No\n");//如果长度为奇的话则表示无法配对成功 else { a[++top]=s[0]; for(int i=1; i<d; i++) { if(fun(a[top],s[i])) { top--; //如果配对成功出栈 } else { top++; a[top]=s[i]; //否则继续入栈 } } if(top<0) printf("Yes\n");//如果栈为空则表示可以配对成功 else printf("No\n"); } } return 0; }
或者:
-
-
(2)第二种方法(栈) #include <iostream> #include <algorithm> #include <cstdio> #include <stack> using namespace std; stack <char>s; bool cmp(char a,char b) { return (a=='['&&b==']')||(a=='('&&b==')'); } int main() { int t; cin>>t; getchar(); char str[10010]; while(t--) { gets(str); while(!s.empty()) s.pop(); int i; for(i=0;str[i]!='\0';i++) { if(s.empty()||!cmp(s.top(),str[i])) s.push(str[i]); else s.pop(); } if(s.empty()) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
-
-