题目描述
请写一个程序,判断给定表达式中的括号是否匹配,表达式中的合法括号为”(“, “)”, “[", "]“, “{“, ”}”,这三个括号可以按照任意的次序嵌套使用。
输入
有多个表达式,输入数据的第一行是表达式的数目,每个表达式占一行。
输出
对每个表达式,若其中的括号是匹配的,则输出”yes”,否则输出”no”。
样例输入
4
[(d+f)*{}]
[(2+3))
()}
[4(6]7)9
样例输出
yes
no
no
no
思路
这道题只是判断符号是不是匹配,所以我们利用栈的知识,栈中只存括号,等到字符串遍历结束,通过栈是不是空来判断结果。
1.如果字符为"("、"["、"{",就入栈。
2.如果字符为")"、"]"、"}",就判断,若是栈为空,则入栈对应第3种情况;若栈不为空,则与栈顶元素匹配,若是匹配成功,栈顶元素出栈,否则该字符进栈,这里对应样例的第4种情况。
3.如果字符为其他,则跳过。
4.若栈为空,输出yes,否则输出no。然后清空栈。
代码
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <stack>
using namespace std;
//匹配
bool match(char a,char b){
if(a=='['&&b==']') return true;
else if(a=='{'&&b=='}') return true;
else if(a=='('&&b==')') return true;
else return false;
}
int main(){
int n;
string str;
stack<char> st;
while(~scanf("%d",&n)){
while(n--){
cin>>str;
int len=str.length();
for(int i=0;i<len;i++){
if(str[i]=='{'||str[i]=='['||str[i]=='('){
st.push(str[i]);//入栈
}else if(str[i]=='}'||str[i]==']'||str[i]==')'){
if(st.empty()==false){//栈不为空
if(match(st.top(),str[i])==true){//匹配成功
st.pop();
}
else{//匹配失败
st.push(str[i]);
}
}else{//栈为空,直接入栈
st.push(str[i]);
}
}else continue;
}
if(st.empty()==true) cout<<"yes"<<endl;//输出
else cout<<"no"<<endl;
while(st.empty()!=true){//清空栈,用于下一个字符串
st.pop();
}
}
}
return 0;
}