文章
9
粉丝
1
获赞
119
访问
2.2k
注意点:首个元素直接入栈、非空才开始判断是否左括号且入栈,是为了避免各种异常处理,以及匹配成功时 pop 不溢出。
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
while(getline(cin , s)){
stack<char> st;
for(int i = 0; i < s.size(); i++){
if(!st.empty()){
if(s[i] == '(' || s[i] == '['){
st.push(s[i]); // 左括号继续入栈
} else if(st.top() == '(' && s[i] == ')' || st.top() == '[' && s[i] == ']'){
st.pop(); // 匹配则出栈
}else st.push(s[i]); // 即不是左,也不匹配,则入栈
} else st.push(s[i]); // 空则入栈,任意字符
}
if(st.empty()) cout << "YES" << endl;
else cout << "NO" << endl;
}
}
登录后发布评论
暂无评论,来抢沙发