673:Parentheses Balance

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37754288/article/details/81909693

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

猜你喜欢

转载自blog.csdn.net/qq_37754288/article/details/81909693