Parentheses Balance

You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
(a) if it is the empty string
(b) if A and B are correct, AB is correct,
© if A is correct, (A) and [A] is correct.
Write a program that takes a sequence of strings of this type and check their correctness. Your
program can assume that the maximum string length is 128.
Input
The file contains a positive integer n and a sequence of n strings of parentheses ‘()’ and ‘[]’, one string
a line.
Output
A sequence of ‘Yes’ or ‘No’ on the output file.
Sample Input
3
([])
(([()])))
([()])()
Sample Output
Yes
No
Yes
代码

#include<bits/stdc++.h>
using namespace std;
stack<char> str;
int main()
{
    //freopen("F:\\1234.txt","r",stdin);
    //freopen("F:\\12345.txt","w",stdout);
    int t;
    cin>>t;
    getchar();
    while(t--)
    {
        string s;
        getline(cin,s);
        if(s.size()==0)
        {
            cout<<"Yes"<<endl;
            continue;
        }
        int flag=0,flag1=0,cnt1=0,cnt2=0;
        for(int i=0;i<s.size();i++)//倒
        {
            if(s[i]=='('||s[i]=='[')
               cnt1++;
            else
                cnt2++;
            if(cnt2>cnt1)
            {
                flag=1;
                break;
            }
        }
        if(flag==1||cnt1!=cnt2)
        {
            cout<<"No"<<endl;
            continue;
        }
        for(int i=0;i<s.size();i++)//遍历
        {
            if(s[i]=='('||s[i]=='[')
                str.push(s[i]);
            else if(!str.empty())
            {
                int flag2=0;
                if((str.top()=='('&&s[i]==')')||(str.top()=='['&&s[i]==']'))
                    flag2=1;
                if(flag2==1)
                {
                    str.pop();
                    continue;
                }
                else
                {
                    flag1=1;
                    break;
                }
            }

        }
        if(flag1==0)
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43797508/article/details/88693905