• 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;
    }
  • 相关阅读:
    字符串方法
    文件上传路径转虚拟路径
    表结构转excel
    @ModelAttribute
    select
    查询详情在模态框展示
    时间
    mybatis一对多
    bootstrap tab页
    为什么不建议使用WordPress呢?
  • 原文地址:https://www.cnblogs.com/lighter-blog/p/6028330.html
Copyright © 2020-2023  润新知