Try   HackMD

Leetcode 20. Valid Parentheses

有以下幾種'(', ')', '{', '}', '[', ']',判斷是否以正確順序關閉以及組合。

想法

使用堆疊,判斷開關以及順序正確。

程式碼:

def isValid(self, s: str) -> bool:
        list = []
        for i in s:
            if(i=="{"):
                list.append("}")
            elif(i=="["):
                list.append("]")
            elif(i=="("):
                list.append(")")
            else:
                if(len(list)==0):
                    return False
                if(i!=list.pop()):
                    return False
        if(len(list)!=0):
            return False
        return True