题目链接
用栈模拟转换过程,如果当前元素不是 ‘)’ 直接入栈,遇到 ‘)’ 则出栈,直到栈顶是 ‘(’ 出栈结束,最后再弹出 ‘(’,最后栈中的元素就是最终的翻转结果,然后将栈中元素用一个字符串存储,最后返回即可。
class Solution {
public:
string reverseParentheses(string s) {
stack<char> ans;
for(int i = 0; i < s.size(); i++)
{
ans.push(s[i]);
if(s[i] == ')')
{
ans.pop();
string x = "";
while(ans.top() != '(')
{
x += ans.top();
ans.pop();
}
ans.pop();
for(int i = 0; i < x.size(); i++)
ans.push(x[i]);
}
}
string ch = "";
while(!ans.empty())
{
ch += ans.top();
ans.pop();
}
reverse(ch.begin(), ch.end());
return ch;
}
};