题目:
描述
现在,有一行括号序列,请你检查这行括号是否配对。
-
输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[", "]", "(", ")" 四种字符 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No 样例输入
-
3 [(]) (]) ([[]()])
样例输出
-
No No
Yes
-
-
此题考查的是栈的数据结构
-
当待处理元素(即括号)与栈顶元素(即栈顶括号)配对时,进行出栈操作,反之进行入栈操作。
-
若最后的结果是栈为空,则括号匹配,反之不匹配。
-
AC代码之手动构建栈:
-
AC代码之使用STL:#include<iostream> #include<cstdio> #include<cstring> using namespace std; int main() { int n,top,b; string str; cin>>n; while(n--) { top=1; cin>>str; b=str.length(); char *p=new char [b]; p[0]=str[0]; if(b%2==1) { cout<<"No"<<endl; } else if(str[0]==')'||str[0]==']') { cout<<"No"<<endl; } else { for(int i=1;i<b;i++) { p[top]=str[i]; if(p[top-1]=='('&&str[i]==')') { top--; } else if(p[top-1]=='['&&str[i]==']') { top--; } else { top++; } } if(top==0) { cout<<"Yes"<<endl; } else { cout<<"No"<<endl; } } } return 0; }
-
#include<iostream> #include<cstdio> #include<stack> #include<cstring> using namespace std; int main() { int n,b; string str; cin>>n; while(n--) { cin>>str; b=str.length(); if(b%2==1) { cout<<"No"<<endl; } else { stack<char> q; for(int i=0;i<b;i++) { if(q.empty()) { q.push(str[i]); } else if(q.top()=='('&&str[i]==')') { q.pop(); } else if(q.top()=='['&&str[i]==']') { q.pop(); } else { q.push(str[i]); } } if(q.empty()) { cout<<"Yes"<<endl; } else { cout<<"No"<<endl; } } } return 0; }