给定仅包含“()[]{}”六种括号的字符串,请你判断该字符串中,括号的匹配是否是合法的,也就是对应括号的数量、嵌套顺序完全正确。
输入格式:
第一行一个整数T(T<=10)
其后T行每行一个字符串只包含[{()}]六种字符(字符串长度2e5以内)
输出格式:
对于每个字符串,匹配输出Yes,否则输出No
输入样例:
2
{()[]}
([)]
结尾无空行
输出样例:
Yes
No
结尾无空行
#include<iostream>
#include<stdlib.h>
#include<string>
#include<string.h>
#include<stack>
using namespace std;
int judge(string str){
stack<char>s;
int flag=0;
for(auto i:str){
if(i=='('||i=='['||i=='{')s.push(i);
else{
if(s.empty()){return 0;}
else{
if(i==')'){
if(s.top()!='('){
return 0;
}
else s.pop();
}
if(i==']'){
if(s.top()!='['){
return 0;
}
else s.pop();
}
if(i=='}'){
if(s.top()!='{'){
return 0;
}
else s.pop();
}
}
}
}
return s.empty();
}
int main(){
int n;
string str;
cin>>n;
for(int i=0;i<n;i++){
cin>>str;
if(!judge(str))printf("No\n");
else printf("Yes\n");
}
system("pause");
}