uva673嵌套括号

xiaoxiao2021-02-28  96

题意:紫书

这题比较简单,用一个维护一个栈,遇到左括号入栈,右括号判断栈顶,如果匹配则出栈。

注意:1、输入存在空串 所以要用getline.

  2、此题是嵌套括号而不是括号匹配,因此像[ ( ] ) 输出是no 而不是yes

ac代码:

#include<cstdio> #include<cstring> #include<stack> #include<string> #include<iostream> using namespace std;//wa example:[(]) const int maxn=200; char c[maxn]; int T; bool solve(){ stack<char> s; for(int i=0;i<strlen(c);i++){ if(c[i]=='['||c[i]=='(') s.push(c[i]); else if(c[i]==']'&&!s.empty()&&s.top()=='[') s.pop(); else if(c[i]==')'&&!s.empty()&&s.top()=='(') s.pop(); else return false; } if(s.empty()) return true; return false; } int main(){ //freopen("out.txt","w",stdout); while(cin>>T){ cin.get(); for(int cas=1;cas<=T;cas++){ memset(c,0,sizeof(c)); cin.getline(c,maxn); if(solve()) cout<<"Yes"<<endl; else cout<<"No"<<endl; } } return 0; }

转载请注明原文地址: https://www.6miu.com/read-1950226.html

最新回复(0)