Test instructions approximate: Enter a sequence of parentheses that includes "()" and "[]" to determine whether it is legal. The specific rules are as follows:
1. Empty string legal.
2. If both A and B are legal, then AB is also legal.
3. If a is legal, then [a] and (a) are legal.
Ideas:
Initialize a stack, enter a sequence, and then scan:
1. The sequence length is definitely an even number (including 0);
2. If "[" or "(") it is pressed into the stack;
3. If ")" or "]", then the value of the element at the top of the current stack is determined,
If the match is not successful, then no more matching, it must not be successful!
The code is as follows:
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><strong> #include <cstdio> #include <iostream> #include <cstring> #include <stack> using namespace Std;const int Maxn=201314;char str[maxn];stack<char> s;//used to store the left symbol stack void init () {while (!s.empty ()) S.pop ();} void Solve () {int len=strlen (str); if (len%2!=0)//If Len is odd, prove impossible to match success! {cout<< "No" <<endl; return; } for (int i=0;i<len;i++) {if (str[i]== ' [' | | | str[i]== ' (') S.push (Str[i]);//If it is (or [is] pressed directly into the stack! else {char now=s.top (); if ((now== ' (' &&str[i]== ') ') | | (now== ' [' &&str[i]== ']) If you meet) or] sign, then make a judgment! {S.pop (); } else {cout<< "No" <<endl; return; }}} cout<< "Yes" <<endl; return;} int main () {int n; cin>>n; while (n--) {Cin>>str; Init (); Solve (); } return 0;} </strong></span>
Balanced brackets Uva-673