leetcode 1021. 删除最外层的括号(C++、python)

有效括号字符串为空 ("")"(" + A + ")" 或 A + B,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。例如,"""()""(())()" 和 "(()(()))" 都是有效的括号字符串。

如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。

给出一个非空有效字符串 S,考虑将其进行原语化分解,使得:S = P_1 + P_2 + ... + P_k,其中 P_i 是有效括号字符串原语。

对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。

示例 1:

输入:"(()())(())"
输出:"()()()"
解释:
输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())",
删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。

示例 2:

输入:"(()())(())(()(()))"
输出:"()()()()(())"
解释:
输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))",
删除每隔部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。

示例 3:

输入:"()()"
输出:""
解释:
输入字符串为 "()()",原语化分解得到 "()" + "()",
删除每个部分中的最外层括号后得到 "" + "" = ""。

提示:

S.length <= 10000

S[i] 为 "(" 或 ")"

S 是一个有效括号字符串

C++

class Solution {
public:
    string removeOuterParentheses(string S) 
    {
        string res="";
        int n=S.length();
        if(0==n)
        {
            return "";
        }
        stack<char> tmp;
        tmp.push('(');
        for(int i=1;i<n;i++)
        {
            if('('==S[i])
            {
                if(tmp.empty())
                {
                    tmp.push('(');
                }
                else
                {
                    tmp.push('(');
                    res+='(';                    
                }
            }
            else
            {
                if(1==tmp.size())
                {
                    tmp.pop();
                }
                else
                {
                    if('('==tmp.top())
                    {
                        tmp.pop();                       
                    }
                    else
                    {
                        tmp.push(')');
                    }
                    res+=')';
                }                
            }
        }
        return res;
    }
};

python

class Solution:
    def removeOuterParentheses(self, S: str) -> str:
        n=len(S)
        if 0==n:
            return ""
        res=""
        tmp=['(']
        for i in range(1,n):
            if '('==S[i]:
                if len(tmp)!=0:
                    res+='('
                tmp.append('(')
            else:
                if 1==len(tmp):
                    del tmp[0]
                else:
                    if '('==tmp[-1]:
                        del tmp[-1]
                    else:
                        tmp.append(')')
                    res+=')'
        return res
        

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/89406609
今日推荐