【Leetcode_总结】1021. 删除最外层的括号 - python

Q:

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

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

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

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


链接:https://leetcode-cn.com/problems/remove-outermost-parentheses/

思路:使用一个栈,如何栈内是有效括号,便去头去尾,加到res中

代码:

class Solution:
    def removeOuterParentheses(self, S: str) -> str:
        stack = []
        res = ''
        for i in range(len(S)):
            stack.append(S[i])
            if stack.count('(') == stack.count(')'):
                res+=''.join(stack[1:-1])
                stack = []
        return res

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/89448788
今日推荐