Original question
Description
You are given a string consisting of parentheses () and []. A string of this type are said to be correct:
-
(a)
-
If it is the empty string
-
(b)
-
If A and B are correct, AB is correct,
-
(c)
-
If A is correct, (a ) and [a ] is correct.
Write a program, takes a sequence of strings of this type and check their correctness. Your program can assume, the maximum string length is 128.
InputThe file contains a positive integer
Nand a sequence of
NStrings of parentheses()and[], one string a line.
OutputA sequence ofYesOrNoOn the output file.
Sample Input
3 ([]) (([()]) ([[()])) ([() [] ()] () ()
Sample Output
Yesnoyes
Analysis: Simple problem, directly with the stack can be
My Code:
1#include <iostream>2#include <stack>3#include <cstring>4#include <cstdio>5 using namespacestd;6 7 Chars[ Max];8 9 BOOLIfpop (Const CharAConst Charb)Ten { One if(A = ='('&&b = =')')return 1; A if(A = ='['&&b = =']')return 1; - return 0; - } the - - intMain () - { + intT; -CIN >>T; + GetChar (); A while(t--) at { -stack<Char>Z; - gets (s); - if(s[0] ==' /') - { -Puts"Yes"); in Continue; - } to Else + { - for(inti =0; s[i]!=' /'; i++) the { * if(Z.empty ()) $ {Panax Notoginseng Z.push (S[i]); - } the Else + { A if(Ifpop (Z.top (), s[i])) the { + Z.pop (); - } $ Else $ { - Z.push (S[i]); - } the } - }Wuyi if(Z.empty ()) puts ("Yes"); the ElsePuts"No"); - } Wu - About } $ return 0; -}
UVA 673 parentheses Balance problem solving experience