文章

74

粉丝

0

获赞

98

访问

8.9k

头像
括号的匹配 题解(stack和map容器):
P1067 中山大学机试题
发布于2025年8月11日 17:39
阅读数 208

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

map<char, int> rk = {{'{', 4}, {'[', 3}, {'(', 2}, {'<', 1}};
map<char, char> match  = {{'}', '{'}, {']', '['}, {')', '('}, {'>', '<'}};

string judge(string s){
	stack<char> st;
	for(char &ch : s){
		
		if(ch == '{' || ch == '[' || ch == '(' || ch == '<'){ // 若输入为左括号
			if(!st.empty() && rk[ch] > rk[st.top()]) return "NO";
			else st.push(ch);
		} else { // 若为右括号
			if(!st.empty() && match[ch] == st.top()) st.pop(); 
			else return "NO";
		}
	}
	
	if(st.empty()) return "YES";
	else return "NO";
}

int main(){
	int n; cin >> n;
	while(n --){
		string s;
		cin >> s;
		cout << judge(s) << '\n';
	}
	
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发