https://leetcode-cn.com/problems/valid-parentheses/
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
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 == []