zoukankan      html  css  js  c++  java
  • 利用栈实现括号匹配

    #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 '';
        }
    }


    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;
    }
  • 相关阅读:
    DOM getElementById
    百度之星2014
    游艇租借
    2014年acm亚洲区域赛·鞍山站
    UVALive 4255 Guess
    UVA 10054 The Necklace
    UVA 10047 The Monocycle
    UVA 11624 Fire!
    第九届黑龙江省赛
    剑指offer系列31-----二叉树的下一个节点
  • 原文地址:https://www.cnblogs.com/wangjianupc/p/10587222.html
Copyright © 2011-2022 走看看