0
点赞
收藏
分享

微信扫一扫

Leetcode 1190 反转每对括号间的子串


题目链接

Leetcode 1190 反转每对括号间的子串_字符串


用栈模拟转换过程,如果当前元素不是 ‘)’ 直接入栈,遇到 ‘)’ 则出栈,直到栈顶是 ‘(’ 出栈结束,最后再弹出 ‘(’,最后栈中的元素就是最终的翻转结果,然后将栈中元素用一个字符串存储,最后返回即可。

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;
    }
};


举报

相关推荐

0 条评论