Parentheses Balance
给定一串由()和[]组成的字符串。如果我们规定以下的字符串是合法的字符串:
(1) 如果是空串,那么合法字符串。
(2) 如果A、B是合法的,那么AB也是合法的字符串。
(3) 如果A是合法的,那么(A)和[A]都是合法的字符串。
换言之,如果字符串中离任一一个右括号(即')'或者’]')的最近的未配对左括号是配对的,且所有左右括号都已配对,那么它就是一个合法的字符串。
Input
输入先是一个正整数n,代表有n个字符串。
接下来是n行字符串,每个字符串一行,注意,可能有空串。
Output
对于每组数据,若是合法的字符串,则在单独的一行输出Yes,反之则输出No。
Sample Input
4 ([]) (([()]))) ([()[]()])() (([(])))
Sample Output
Yes No Yes No
经典的括号匹配问题,用栈解决。
左括号入栈,右括号出栈,最终栈空,输出 Yes。注意空行也是yes。
一个栈就解决问题,当时做这题的时候还用两个队列做,我真的是够了
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #include<string.h> #include<iterator> #include<vector> #include<stdlib.h> #include<map> #include<queue> #include<stack> #include<set> #include<sstream> typedef long long ll; using namespace std; int main() { int t; scanf("%d",&t); getchar(); while(t--) { stack<char> s; string str; getline(cin,str); int len = str.length(); for(int i=0;i<len;i++){ if(len == 0) { printf("Yes\n"); continue; } if(str[i]=='('||str[i]=='[') s.push(str[i]); else if(str[i]==')'){ if(s.size()&&s.top()=='(') s.pop(); else s.push(str[i]); } else if(str[i]==']'){ if(s.size()&&s.top()=='[') s.pop(); else s.push(str[i]); } } if(s.size()) printf("No\n"); else printf("Yes\n"); } return 0; }