Bracket balance

Bracket balance

Given a string consisting of () and []. If we stipulate that the following strings are legal strings:
(1) If it is an empty string, then a legal string.
(2) If A and B are legal, then AB is also a legal string.
(3) If A is legal, then (A) and [A] are both legal strings.
Sample Input
3
([])
(([()])))
([()])()
Sample Output
Yes
No
Yes

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
    int n;
    scanf("%d",&n);
    vector<char>s;
    char a[1000];
    int i,m;
    getchar();
    while(n)
    {
    
    
        gets(a);
        m=strlen(a);
        if(m==0)//空字符串
        {
    
    
            printf("Yes\n");
            n--;
            continue;
        }
        for(i=0;i<m;i++)
        {
    
    
            s.push_back(a[i]);//存入容器
        }
        int t;
        while(s.size())
        {
    
    
            t=0;
            for(i=0;i<m-1;i++)
            {
    
    
                if((s[i]=='('&&s[i+1]==')')||(s[i]=='['&&s[i+1]==']'))
                {
    
    
                    s.erase(s.begin()+i);//删除
                    s.erase(s.begin()+i);
                    t++;
                }
            }
            if(t==0)
            {
    
    
                printf("No\n");
                break;
            }
        }
        if(s.size()==0)
        {
    
    
            printf("Yes\n");
        }
        s.clear();
        n--;
    }
}




Guess you like

Origin blog.csdn.net/weixin_51996479/article/details/112916774