UVa673 Parentheses Balance

// UVa673 Parentheses Balance
// 题意:输入一个包含()和[]的括号序列,判断是否合法。
// 具体递归定义如下:1.空串合法;2.如果A和B都合法,则AB合法;3.如果A合法则(A)和[A]都合法。
// 算法:用一个栈。注意输入可能有空串

#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;

int main()
{
        int n;
        scanf("%d", &n); getchar();
        char s[256];
        while(n--)
        {
                gets(s);
        //      puts(s);
                int len=strlen(s);
                stack<char> st;
                char c;
                bool ok=true;
                for(int i=0;i<len&&ok;i++)
                {
                        switch(s[i])
                        {
                                case '(':
                                case '[':
                                        st.push(s[i]);
                                        break;
                                case ')':
                                case ']':
                                        if(st.empty())
                                                ok=false;
                                        else
                                        {
                                                c=st.top(); st.pop();
                                                if(s[i]==')' && c!='(') 
                                                        ok=false;
                                                else if(s[i]==']' && c!='[') 
                                                        ok=false;
                                        }
                                        break;
                        }
                }
                if(ok&&st.empty())
                        printf("Yes
");
                else
                        printf("No
");

        }

    return 0;
}
原文地址:https://www.cnblogs.com/cute/p/3613741.html