Codeup STL(stack):Problem E(括号匹配)

题目描述

请写一个程序,判断给定表达式中的括号是否匹配,表达式中的合法括号为”(“, “)”, “[", "]“, “{“, ”}”,这三个括号可以按照任意的次序嵌套使用。

输入

有多个表达式,输入数据的第一行是表达式的数目,每个表达式占一行。

输出

对每个表达式,若其中的括号是匹配的,则输出”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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值