673-parentheses Balance
Time limit:3.000 seconds
Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=103&page=show_ problem&problem=614
You are given a string consisting of parentheses () and []. A string of this type was 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 that takes a sequence of the strings of this type and check their correctness. Your program can assume this maximum string length is 128.
Input
The file contains a positive integer n and a sequence of n strings of parentheses () and [], one str ing a line.
Output
A sequence of Yes or No on the output file.
Sample Input
3
([])
(([[)])) ([()
[] ()]) ()
Sample Output
Yes
No
Yes
Tip: Add an element to the bottom of the stack to reduce the amount of code.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Complete code:
/*0.029s*/#include <cstdio> #include <cstring> #include <stack> using namespace std;
Stack<char> s;
Char str[130];
int main (void) {int t;
scanf ("%d", &t);
GetChar ();
while (t--) {gets (str);
int len = strlen (str);
if (Len & 1) puts ("No");
else {if (!s.empty ()) S.pop (); S.push (' 0 ');///"token" for (int i = 0; i < len; ++i) {if (str[i] = = ' (' | | | str[i ')
= = ' ['] S.push (Str[i]);
else if (str[i] = = ') {if (s.top () = = ' () s.pop ();
else {s.push (' 1 ');
Break
} else///'] ' {if (s.top () = ' ['] S.pop ();
else {s.push (' 1 ');
Break }} puts (S.top () = ' 0 '?
"Yes": "No");
} return 0; }