Skip to content

Latest commit

 

History

History
44 lines (41 loc) · 966 Bytes

20.md

File metadata and controls

44 lines (41 loc) · 966 Bytes

题目地址

https://leetcode-cn.com/problems/valid-parentheses/

解答1

def isValid(s):
    """ 有效的括号 """
    right = ""
    for i in s:
        if i == "(":
            right += ")"
        elif i == "[":
            right += "]"
        elif i == "{":
            right += "}"
        else:
            if i in [")", "]", "}"]:
                if not right or i != right[-1]:
                    return False
                else:
                    right = right[:-1]
    return not right

解答2

def isValid(s):
    """ 有效的括号 """
    hashmap = {
        ")": "(",
        "}": "{",
        "]": "[",
    }

    stack = []
    for i in range(len(s)):
        if s[i] in hashmap.keys():
            topElement = "#" if not stack else stack.pop()
            if topElement != hashmap[s[i]]:
                return False
        elif s[i] in hashmap.values():
            stack.append(s[i])
    return stack == []