673:Parentheses Balance

Parentheses Balance

之前脑子可能坏掉了。。。简单的栈的应用,要注意的一个地方是一定要用 fgets ,因为如果是空串的话 scanf 会直接读下一行。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 128 + 5;
int n;
char s[maxn];
int main()
{
    // freopen("data.in","r",stdin);
    // freopen("data.out","w",stdout);
    scanf("%d",&n);
    getchar();
    while(n--){
        stack<char>S;
        fgets(s,maxn,stdin);
        s[strlen(s)-1] = 0;
        int i = 0;
        for(;s[i];i++){
            if(s[i] == '(' || s[i] == '[') S.push(s[i]);
            else{
                if(S.empty()) break;
                if(s[i] == ')' && S.top() == '(' ||
                    s[i] == ']' && S.top() == '['){
                    S.pop();
                }
                else break;
            }
        }
        printf("%s\n",s[i] || S.size() ? "No" : "Yes");
    }
    return 0;
}

 

posted @ 2018-08-21 16:22  ACLJW  阅读(108)  评论(0编辑  收藏  举报