1021. Remove Outermost Parentheses删除最外层的括号

网址:https://leetcode.com/problems/remove-outermost-parentheses/

使用栈的思想,选择合适的判断时机

class Solution {
public:
    string removeOuterParentheses(string S)
    {
        stack<char> s_ch;
        string ans;
        stack<char> temp;
        int l = 0, r = 0;
        for(int i = 0; i<S.size(); i++)
        {
            if(S[i] == '(')
            {
                s_ch.push(S[i]);
                l++;
            }
            else
            {
                r++;
                if(s_ch.size() % 2 == 1 && r==l)
                {
                    ans = ans + S.substr(i+1-s_ch.size(), s_ch.size()-1);
                    s_ch = temp;
                    l = 0; r = 0;
                }
                else
                    s_ch.push(S[i]);
            }
        }
        return ans;
    }
};

删除最外层的括号

猜你喜欢

转载自www.cnblogs.com/tornado549/p/10668900.html
今日推荐