文章

83

粉丝

2

获赞

592

访问

63.8k

头像
括号匹配问题 题解:
P1296 北京大学机试题
发布于 2026年3月
阅读数 794

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
    string s;

    while (getline(cin, s)) {
        stack<int> st;
        string res(s.size(), ' '); 

        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(') {
                st.push(i);
            } else if (s[i] == ')') {
                if (!st.empty()) {
                    st.pop(); 
                } else {
                    res[i] = '?'; 
                }
            }
        }

        while (!st.empty()) {
            res[st.top()] = '$';
            st.pop();
        }

        cout << s << endl;
        cout << res << endl;
    }

    return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发