NYOJ 2 括号匹配问题

来源:互联网 发布:淘宝三颗心要多少好评 编辑:程序博客网 时间:2024/06/05 09:02
//RuntimeError#include<iostream>#include<cstdio>#include<stack>#include<string>using namespace std;stack<char>s;int main(){int n;cin>>n;while(n--){string expr;cin>>expr;int len=expr.length();for(int i=0;i<len;i++){if((expr[i]=='(') || (expr[i]=='['))s.push(expr[i]);else if(expr[i]==')'  ){if(s.top()=='(')s.pop();elses.push(expr[i]);}else if(expr[i]==']'){if(s.top()=='[')s.pop();elses.push(expr[i]);}}if(s.empty())printf("Yes\n");elseprintf("No\n");while(!s.empty())s.pop();}return 0;}//为啥最后不能直接用  栈不空就弹出呢?感觉可能与栈的非法访问有关//AC代码#include<iostream>#include<cstdio>#include<stack>#include<string>using namespace std;stack<char>s;int main(){int n;s.push('#');cin>>n;while(n--){string expr;cin>>expr;int len=expr.length();for(int i=0;i<len;i++){if((expr[i]=='(') || (expr[i]=='['))s.push(expr[i]);else if(expr[i]==')'  ){if(s.top()=='(')s.pop();elses.push(expr[i]);}else if(expr[i]==']'){if(s.top()=='[')s.pop();elses.push(expr[i]);}}if(s.top()=='#')printf("Yes\n");elseprintf("No\n");while(s.top()!='#')s.pop();}return 0;}

原创粉丝点击