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
在这里插入图片描述

方法一:
利用栈:
遍历字符,遇到"(“符号入栈,”)“符号出栈。如果”(“入栈前,栈是空的,那么这个”(“就是最外层的,如果”)“出栈后,栈是空的,那么这个”)“就是最外层的”)"。
其他的符号拼接起来,就是我们要输出的结果。

class Solution:
    def removeOuterParentheses(self, S: str) -> str:
        stack = []
        res = ""
        for char in S:
            if char == "(":
                if stack:
                    res += char
                stack.append(char)
            if char == ")":
                stack.pop()
                if stack:
                    res += char
        return res

执行用时: 44 ms
内存消耗: 13.7 MB

方法二:
单指针计数法:
利用count计数,遇到“(”,count +1, 遇到“)”, count -1。当遍历的符号是“(”时,count=0是最外面的括号,当遍历的符号是“)”时,count = 1是最外层的括号。
其他情况拼接起来,就是要输出的结果。

class Solution:
    def removeOuterParentheses(self, S: str) -> str:
        count = 0
        res = ""
        for char in S:
            if char == "(" and count != 0:
                res += char
            if char == ")" and count != 1:
                res += char
            count += 1 if char == "(" else -1
        return res

执行用时: 44 ms
内存消耗: 13.5 MB

猜你喜欢

转载自blog.csdn.net/weixin_45455015/article/details/110345201