文章

9

粉丝

1

获赞

119

访问

2.2k

头像
括号匹配 题解:
P1501 西北工业大学机试题
发布于2026年2月10日 17:05
阅读数 110

  1. 注意点:首个元素直接入栈、非空才开始判断是否左括号且入栈,是为了避免各种异常处理,以及匹配成功时 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;
    }
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发