利用栈实现括号匹配

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
using namespace std;


char toRight(char ch){
    switch(ch){
        case '{': return '}';
        case '[': return ']';
        case '(': return ')';
        case '<': return '>';
        default :return '\0';
    }
}


bool isLeft(char ch){
    return ch=='{'||ch=='('||ch=='['||ch=='<';
}
bool isRight(char ch){
    return ch=='}'||ch==')'||ch==']'||ch=='>';
}
int main(){
    stack<char> stk;
    char ch;
    while(cin>>ch){
        cout<<ch<<endl;
        if(isLeft(ch)){
            stk.push(ch);
        }
        else if(isRight(ch)){
            if(stk.empty()||toRight(stk.top())!=ch){
                cout<<"error"<<endl;
                return 0;
            }
            else
                stk.pop();
        }
    }
    if(stk.empty()){
        cout<<"ok"<<endl;
    }
    else{
        while(!stk.empty()){
            cout<<toRight(stk.top());
            stk.pop();
        }
    }
    return 0;
}
posted @ 2018-04-25 21:29  UnderScrutiny  阅读(276)  评论(0编辑  收藏  举报