题目描述
请写一个程序,判断给定表达式中的括号是否匹配,表达式中的合法括号为”(“, “)”, “[", "]“, “{“, ”}”,这三个括号可以按照任意的次序嵌套使用。
输入
有多个表达式,输入数据的第一行是表达式的数目,每个表达式占一行。
输出
对每个表达式,若其中的括号是匹配的,则输出”yes”,否则输出”no”。
样例输入
4 [(d+f)*{}] [(2+3)) ()} [4(6]7)9
样例输出
yes no no no
#include<bits/stdc++.h>
using namespace std;
const int maxn=1001;
stack<char> st;
int n;
char getType(const char c){//判断是哪个左括号或右括号
char bktSet[]="([{}])";
int i;
for(i=0;i<6;i++){
if (bktSet[i]==c) break;
}
if(i<3) return 'l';
else if(i<6) return 'r';
else return 'n';
}
bool match(const char cl,const char cr){//判断栈顶弹出的括号与当前括号是否能配对
if(cl=='(') return cr==')'? true:false;
else if(cl=='{') return cr=='}' ? true:false;
else if(cl=='[') return cr==']' ? true:false;
else return false;
}
int main(){
cin>>n;
while(n--){
while (!st.empty())//栈定义在外面,要记得每次清空
st.pop();
char ch[maxn];
cin>>ch;
int i=0;
char c;
for(int i=0;ch[i]!='\0';i++){
if(getType(ch[i])=='r'){//if(ch[i]=='}'||ch[i] ==']'||ch[i]==')')
if (!st.empty()){
c=st.top();
if(match(c,ch[i])) st.pop();//if((c=='('&&ch[i]==')')||(c=='['&&ch[i]==']')|| (c =='{'&&ch[i]=='}'))
else st.push(ch[i]);
}
else{
st.push(ch[i]);
}
}
else if(getType(ch[i])=='l'){//if(ch[i]=='{'||ch[i] =='['||ch[i]=='(')
st.push(ch[i]);
}
}
if (st.empty())
cout << "yes" << endl;
else
cout << "no" << endl;
}
return 0;
}