Files
exercises/pojcs101_M03704_brackets.cpp
2026-08-06 23:20:25 +08:00

52 lines
1.2 KiB
C++

#include <iostream>
#include <stack>
#include <vector>
using namespace std;
struct Bracket {
bool is_right;
size_t index;
bool operator<(const Bracket& other) const {
return index < other.index;
}
};
string get_unmatched_brackets_string(const string& s) {
stack<Bracket> brackets;
vector<Bracket> unmatched_brackets;
string printed_string(s.size(), ' ');
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == '(') {
brackets.push({.is_right = false, .index = i});
} else if (s[i] == ')') {
if (brackets.empty()) {
unmatched_brackets.push_back({.is_right = true, .index = i});
} else {
brackets.pop();
}
}
}
while (!brackets.empty()) {
unmatched_brackets.push_back(brackets.top());
brackets.pop();
}
for (const auto& [is_right, index] : unmatched_brackets) {
printed_string[index] = is_right ? '?' : '$';
}
return printed_string;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
while (getline(cin, s) && !s.empty()) {
cout << s << endl << get_unmatched_brackets_string(s) << endl;
}
return 0;
}