Leetcode 1021. Remove Outermost Parentheses

括号匹配想到用栈来做:

class Solution:
    def removeOuterParentheses(self, S: str) -> str:
        size=len(S)
        if size==0:
            return ""
        i=0
        strings=[]
        while i<size:
            stack=[S[i]]
            string=S[i]
            i+=1
            while i<size:
                if S[i]=='(':
                    stack.append(S[i])
                else:
                    stack.pop()
                string+=S[i]
                i+=1
                if not stack:
                    break
            strings.append(string)
        strings=list(map(lambda x:x[1:-1],strings))
        return ''.join(strings)

其实因为括号都是匹配好了的,只有左括号和右括号两种情况,没必要真的维护一个栈,栈是一种思想,未必要真的实现出来.只需要记录一下数就行.

class Solution:
    def removeOuterParentheses(self, S: str) -> str:
        if len(S)==0:
            return ""
        ans=[]
        stack=0
        for s in S:
            if s=='(' and stack>0:
                ans.append(s)
            elif s==')' and stack>1:
                ans.append(s)
            stack+=1 if s=='(' else -1
        
        return ''.join(ans)

 

你可能感兴趣的:(Leetcode 1021. Remove Outermost Parentheses)