文章

85

粉丝

0

获赞

482

访问

9.9k

头像
括号的匹配 题解:
P1067 中山大学机试题
发布于2026年3月5日 16:08
阅读数 249

#include <bits/stdc++.h>
using namespace std;

int getval(char c){
	switch(c){
		case '{':return 4;
		case '[':return 3;
		case '(':return 2;
		case '<':return 1;
		default:return 0;
	}}

bool equal(char a,char b){
	return (a=='{'&&b=='}')||(a=='['&&b==']')||(a=='('&&b==')')||(a=='<'&&b=='>');
}

int main(){
	int n;
	cin>>n;
	string st;
	for(int i=0;i<n;i++){
		cin>>st;
		stack<char> s;
		int flag =1;
		for(int i=0;i<st.length();i++){
			if(st[i]=='{'||st[i]=='('||st[i]=='['||st[i]=='<'){
				if( !s.empty()&&getval(st[i])>getval(s.top())){
					flag=0;
					break;}
				s.push(st[i]);
			}
			else{
				if(s.empty()||!equal(s.top(),st[i])) {
					flag=0;
					break;
				}
				s.pop();
			}
		}

		if(flag==1&&s.empty()){
			cout<<"YES"<<endl;}
		else {
			cout<<"NO"<<endl;
		}
	}
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发