文章

34

粉丝

9

获赞

5

访问

8.8k

头像
括号匹配的问题 题解:栈 + 简单判断
P4933
发布于2024年6月28日 21:39
阅读数 210

#include <iostream>
#include <stack>

using namespace std;

int main(){
	string s;
	cin >> s;
	stack<char> st; 
	
	for(int i = 0;i < s.size();i ++){
		if(s[i] == '[' || s[i] == '('){
			st.push(s[i]);
		}else if(s[i] == ')'){
			if(st.empty()){
				cout << "NO" << endl;
				return 0;
			}else{
				if(st.top() == '('){
					st.pop();
				}else{
					cout << "NO" << endl;
					return 0;
				}
			}
		}else if(s[i] == ']'){
			if(st.empty()){
				cout << "NO" << endl;
				return 0;
			}else{
				if(st.top() == '['){
					st.pop();
				}else{
					cout << "NO" << endl;
					return 0;
				}
			}
		}
	}
	
	if(st.empty()){
		cout << "YES" << endl;
	}else {
		cout << "NO" << endl;
	}
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发