栈 NYOJ 2 (括号配对问题)

来源:互联网 发布:顶点网络微博平台代理 编辑:程序博客网 时间:2024/05/21 22:39

访问栈顶元素(a.top())时要保证栈非空!!!!!!!!!!!!!
runtimerror了两次。。。。。注意else 和if逻辑~~~

描述
现在,有一行括号序列,请你检查这行括号是否配对。
输入
第一行输入一个数N(0

#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<sstream>#include<algorithm>#include<stack>using namespace std;int len,ok;char s[10005];stack<char>a;int main(){    int t;    scanf("%d",&t);    while(t--){        scanf("%s",s);        len=strlen(s);        ok=1;        while(!a.empty()){            a.pop();        }        for(int i=0;i<len;i++){            if(s[i]=='('||s[i]=='['){                a.push(s[i]);            }            else if(s[i]==')'){                if(a.empty()){                    ok=0;break;                }                else if(a.top()=='('){a.pop();}                else if(a.top()=='['){ok=0;break;}            }            else if(s[i]==']'){                if(a.empty()){                    ok=0;break;                }                if(a.top()=='['){a.pop();}                else if(a.top()=='('){ok=0;break;}            }        }        if(ok&&a.empty())cout<<"Yes"<<endl;        else cout<<"No"<<endl;    }    return 0;}
1 0
原创粉丝点击