文章

33

粉丝

42

获赞

3

访问

8.2k

头像
括号的匹配 题解:
P1067 中山大学2019年机试题
发布于2024年3月23日 15:23
阅读数 259

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <string>
using namespace std;
int main(){
	int val[127];
	int n;
	val['<'] = 1,val['('] = 2,val['['] = 3,val['{'] = 4;
	cin >> n;
	while(n--){
		string str;
		stack<char> st;
		cin >>str;
		for(int i = 0;i <str.length();i++){
			if(str[i] == '<' || str[i] == '(' ||str[i] == '[' ||str[i] == '{'){
				if(!st.empty()&&val[str[i]] > val[st.top()])
				  goto GG;
				else
				  st.push(str[i]);
			}
			else{
				if(st.empty())
				   goto GG;
				if((str[i] == '>'&&st.top() == '<') ||(str[i] == ')'&&st.top() == '(')||(str[i] == ']'&&st.top() == '[')||(str[i] == '}'&&st.top() == '{'))
				   st.pop();
				else goto GG;
			}
		}
		if(!st.empty())
		   goto GG;
	    cout <<"YES"<<endl;
	    continue;
		GG:
			cout <<"NO"<<endl;
	}
	return 0...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发