nyoj02 括号配对问题 及re问题解决

利用栈实现括号配对

左括号入栈,遇到右括号的时候查看栈顶是否为配对的左括号,

如果是,则弹出栈顶元素(这时一对括号就处理了)

如果不是,则入栈(不过这里需要检查一下栈是否为空,我入栈之前没有检查是不是空,导致了runtime error)

栈为空的情况下stack.top()访问会出错

比如()]

在扫描到]检查栈顶元素stack.top()的时候就会有问题,因为这时栈内为空,所以要先检查栈是否为空

#include <iostream>
#include<stack>
#include<string>
using namespace std;
int result[101] = {0};
int main(int argc, char** argv) {
    int n;
    cin>>n;
    int index = n;
    while(n--){
        string s;
        cin>>s;    
        stack<char> cs;
        for(int i= 0;i<s.size();i++){
            switch(s.at(i)){
                case '(':case '[':
                    cs.push(s.at(i));
                    break;
                case ')':
                    if(cs.empty()||cs.top()!='('){//如果栈顶不是配对的左括号,则把右括号入栈,检查栈是否为空,不然会RE
                        cs.push(s.at(i));
                    }else if(cs.top()=='('){
                        cs.pop();
                    }
                    break;
                case ']':
                    if(cs.empty()||cs.top()!='['){
                        cs.push(s.at(i));
                    }else if(cs.top()=='['){
                        cs.pop();
                    }
                    break;
                default:
                    break;
            }
        }
        if(cs.empty()){
            result[n] = 1;
        }
    }
    while(index--){
        if(result[index]==1){
            cout<<"Yes"<<endl;
        }else{
            cout<<"No"<<endl;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zhaoGavin/p/8619482.html