问题:
给定字符串,按照括号的优先级对字符串进行反转,输出最后不带括号版本的序列
比如:
输入:(ab(love)cd)
输出:dcloveba
解释:
先反转love得到:(abevolcd)
继续反转得:dcloveba
#include<bits/stdc++.h>
using namespace std;
//v1笨。。
void helper(string& input, int l, int r) {
int left,count = 0;
//在区间[l+1,r-1]内检测是否存在括号,若无则不会进入下一轮递归
for (int i = l+1; i <= r-1; ++i) {
if (input[i] == '(') {
++count;
if (count == 1) {
left = i;
}
}
if (input[i] == ')') {
--count;
if (count == 0) {
helper(input, left, i);
}
}
}
//注意它是左闭右开的。。。
reverse(input.begin() + l + 1, input.begin() + r);
}
//v2 一次性遍历出所有括号的位置,然后逐个括号处理
//凡是左右配对问题都可考虑栈
void helper(string& input) {
stack<int> left; //记录每个左括号的位置
//vector<pair<int, int>> parenthesis;//测试用
for (int i = 0; i <= input.size(); ++i) {
if (input[i] == '(') {
left.push(i);//记录左括号位置,等待配对
}
if (input[i] == ')') {
int l = left.top();
left.pop();
//注意它是左闭右开的。。。
reverse(input.begin() + l+1, input.begin() + i);
//parenthesis.push_back({l,i});//测试用
}
}
//测试用
//for (auto x : parenthesis) {
//
// //cout << x.first << ' ' << x.second << endl;
//}
}
int main() {
string input;
getline(cin,input);
//helper(input, 0, input.size() - 1);
helper(input);
for (int i = 0; i < input.size(); ++i) {
while (input[i] == '(' || input[i] == ')') {
input.erase(input.begin()+i);
}
}
cout << input << endl;
return 0;
}