Test instructions to determine if the input bracket sequence is paired
Stack base application stack the top element matches the input character. Note that the bracket sequence can be empty
STL Stack
#include <bits/stdc++.h>using namespace Std;int main () { int cas; char c; Cin >> CAs; GetChar (); while (cas--) { stack<char> s; while ((c = GetChar ()) = ' \ n ') { if (S.empty ()) S.push (c); else if ((c = = ') ' && s.top () = = ' (') | | (c = = '] ' && s.top () = = ' [')] s.pop (); else S.push (c); } Puts (S.empty ()? "Yes": "No"); } return 0;}
Array simulation Stack
#include <cstdio>using namespace Std;int main () { int cas, top; Char s[200], C; scanf ("%d", &cas); GetChar (); while (cas--) { top = 0; while ((c = GetChar ()) = ' \ n ') { if (top = = 0) s[top++] = C; else if (s[top-1] = = ' (' && c = = ') ' | | s[top-1] = = ' [' && c = = '] ') --top; else s[top++] = c; } Puts (top? "No": "Yes"); } return 0;}
You are given a string consisting of parentheses () and []. A string of this type are said to becorrect:
-
(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 integerNand a sequence ofNStrings of parentheses() and[], one string a line.
OutputA sequence ofYesorNoOn the output file.
Sample Input
3 ([]) (([()]) ([[()])) ([() [] ()] () ()
Sample Output
Yesnoyes
UVa 673 parentheses Balance (bracket pairing stack)