Leetcode 1021. Remove Outermost Parentheses

括號匹配想到用棧來作:app

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)

其實由於括號都是匹配好了的,只有左括號和右括號兩種狀況,不必真的維護一個棧,棧是一種思想,未必要真的實現出來.只須要記錄一下數就行.spa

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)
相關文章
相關標籤/搜索