You are given a string consisting of parentheses () and []. A string of this type is 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 strings of this type and check their correctness. Your program can assume that the maximum string length is 128.
Input
The file contains a positive integer n and a sequence of n strings of parentheses () and [] , one string a line.
Output
A sequence of Yes or No on the output file.
Sample Input
3 ([]) (([()]))) ([()[]()])()
Sample Output
Yes NoYes
注:用堆栈,是(,[就入栈,),]就出栈
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <cctype> #include <iostream> #include <algorithm> #include <vector> #include <stack> #include <deque> #include <queue> #include <set> #include <list> #include <map> #include <string> using namespace std; #define infinity 2147483647 int gcd(int a,int b) { return b==0?a:gcd(b,a%b); } int main() { int n,i,l,flag; char s[1000]; stack<char>ss; while(scanf("%d",&n)!=EOF) { getchar(); while(n--) { gets(s); while(!ss.empty()) { ss.pop(); } flag=1; l=strlen(s); for(i=0;i<l;i++) { if(s[i]=='(' || s[i]=='[') ss.push(s[i]); else if(s[i]==')') { if(ss.empty()) { flag=0; break; } else if(ss.top()=='(') ss.pop(); else { flag=0; break; } } else if(s[i]==']') { if(ss.empty()) { flag=0; break; } else if(ss.top()=='[') ss.pop(); else { flag=0; break; } } } if(flag && ss.empty()) cout <<"Yes" <<endl; else cout <<"No" <<endl; } } return 0; }