给定仅包含“()[]{}”六种括号的字符串,请你判断该字符串中,括号的匹配是否是合法的,也就是对应括号的数量、嵌套顺序完全正确。
输入格式:
第一行一个整数T(T<=10)
其后T行每行一个字符串只包含[{()}]六种字符(字符串长度2e5以内)
输出格式:
对于每个字符串,匹配输出Yes,否则输出No
输入样例:
2
{()[]}
([)]
输出样例:
Yes
No
提示:栈空时,输出栈顶元素会越界。所以第一个字符是’}’、’]’、’)'时就要注意了,这种情况是肯定不满足题意的,直接输出"No",如果进入循环判断就错了。
code:
#include<bits/stdc++.h>
using namespace std;
int main(){
int num;
cin>>num;
for(int i=0; i<num; i++)
{
stack<char> sta;
string str;
cin >> str;
if(str.length()%2 == 0 && str[0] != '}' && str[0] != ']' && str[0] != ')' ) {
for(int j=0; j<str.length(); j++) {
if(str[j]=='{'||str[j]=='('||str[j]=='[') {
sta.push(str[j]);
} else if(str[j]=='}'&&sta.top()=='{') {
sta.pop();
} else if(str[j]==']'&&sta.top()=='[') {
sta.pop();
} else if(str[j]==')'&&sta.top()=='(') {
sta.pop();
} else {
break;
}
}
if(!sta.empty()) {
cout<<"No"<<endl;
} else {
cout<<"Yes"<<endl;
}
} else {
cout<<"No"<<endl;
}
}
return 0;
}