简单应用栈的模拟。先将字符串内已匹配的括号pop掉,剩下的依次储存就好。
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main() {
string str;
while (cin >> str) {
stack<char> stk1, stk2, stk3; // stk1存'[', stk2临时中转, stk3存']'
for (int i = 0; i < str.length(); i++) {
if (!stk2.empty() && stk2.top() == '[' && str[i] == ']') {
stk2.pop();
} else {
stk2.push(str[i]);
}
}
while (!stk2.empty()) {
if (stk2.top() == '[') {
stk2.pop();
stk3.push(']');
} else {
stk2.pop();
stk1.push('[');
}
}
while (!stk1.empty()) {
printf("%c", stk1.top());
stk1.pop();
}
cout << str;
while (!stk3.empty()) {
printf("%c", stk3.top());
stk3.pop();
}
printf("\n");
}
}