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

 

posted @ 2016-11-03 21:42  淡蓝色光  阅读(230)  评论(0)    收藏  举报