STL brackets matching problem

Paired brackets

  • description

Now, there is a line bracketed sequence, whether you check this line paired brackets.

Entry

A first input line number N (0 <N <= 100), expressed N sets of test data. N input rows behind the plurality of sets of input data, each input data is a string S (S is the length of less than 10,000, and S is not empty string), the number of data sets less than five test groups. Ensure that only the data contained in S "[", "]", "(", ")" four kinds of character

Export

Output of each input data per line, if the character string contained in parentheses are paired, output Yes, if the output is not paired No

Sample input

3
[(])
(])
([])
Sample output

No
No
Yes

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

int main(){//就是想练一下STL
    int n;
    cin>>n;//n组测试样例
    char a[10006];
    for(int j=0;j<n;j++){

        memset(a,0,sizeof(a));//每次就初始化一下a字符串
        stack<char> s;//栈
        scanf("%s",a);
        int len=strlen(a);
        if(len%2!=0){//如果是奇数就肯定不能完成配对,就不用再进行下边的for循环
            cout<<"No"<<endl;

        }
        else {
            for(int i=0 ;i<len;i++){//如果左符号就push,如果是右符号就看上一个push是不是和他配对
                if(a[i]==']'&&s.top()=='['&&s.size()){//遍历到右符号,如果配对则出栈
                    s.pop();
                }
               else if(a[i]==')'&&s.top()=='('&&s.size()){
                    s.pop();//出栈,同上
                }
                else s.push(a[i]);//入栈

            }

            if(s.size()==0)cout<<"Yes"<<endl;//如果刚好配对就肯定可以实现栈空
            else cout<<"No"<<endl;

        }




    }







}


STL medium-specific stack, leaving after the first-in, first

  • #include the header file
  • s.top () the top element is the last element of the stack
  • s.pop () out of the stack, s.push () Drawing
  • The number of elements in the stack s.size ()
  • Whether s.empty () determines stack is empty
  • A more advanced use of recursion stack is used, it is recommended Bowen stacks and recursion
Published 18 original articles · won praise 0 · Views 258

Guess you like

Origin blog.csdn.net/qq_42815711/article/details/104339687