zoukankan      html  css  js  c++  java
  • Parentheses Balance (Uva 673) 栈

    题目:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=839&page=show_problem&problem=614

    思路:直接用栈解决即可

       若当前字符和栈顶的字符配对时( “()” 或 “[]” ) ,栈顶出栈。

       若当前字符和栈顶的字符不匹配("[)" 或 "(]" ),则不合法,直接停止遍历,输出 NO。

       否则当前字符入栈。

    /* Parentheses Balance (Uva 673) */
    #include <iostream>
    #include <cstring>
    #include <stack>
    using namespace std;
    
    const int maxn = 100005;
    
    int main(){
        //freopen("input.txt", "r", stdin);
        char s[maxn];
        int n;
        cin >> n;    getchar();
        while(n--){
            stack<char> stk;
            gets(s);
            for(int i=0; i<strlen(s); i++){
                if(stk.empty()){
                    stk.push(s[i]);
                }else{
                    int c = stk.top();
                    if(c == '(' && s[i] == ')' || c == '[' && s[i] == ']'){
                        stk.pop();
                    }else if(c == '(' && s[i] == ']' || c == '[' && s[i] == ')'){
                        break;
                    }else{
                        stk.push(s[i]);
                    }
                }
            }
            
            if(stk.empty())
                cout << "Yes" << endl;
            else
                cout << "No" << endl;
        }
        return 0;
    }
  • 相关阅读:
    linux 第五天
    linux 第四天
    二进制 位运算
    二进制
    java 方法的调用过程
    Linux 第三天
    Linux 第二天
    Linux
    学习了半个多月的TankGame
    学习第一天(spring)
  • 原文地址:https://www.cnblogs.com/lighter-blog/p/6028330.html
Copyright © 2011-2022 走看看