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;
    }
  • 相关阅读:
    Vmstat主要关注哪些数据?
    Swap是个什么东东?
    Buffers与cached啥区别
    做错的题目——关于构造器返回值
    做错的题目——this的指向
    JS判断一个数是否为质数
    数组扁平化
    JS实现快速排序
    正则实现千分符
    获取鼠标的当前位置
  • 原文地址:https://www.cnblogs.com/wangjianupc/p/10587222.html
Copyright © 2011-2022 走看看