20_Valid Parentheses
Input: "(]"
Output: falseInput: "([)]"
Output: falseInput: "{[]}"
Output: trueSolution: using stack
def isValid(s):
"""
:type s: str
:rtype: bool
"""
rule = {'(':')', '[':']', '{':'}'}
stack = [] # store all the unmatched left parentheses
for item in s:
# if the item is left parentheses
if rule.get(item) is not None:
stack.append(item)
# if the item is right parentheses,
# and on it's left, there has left parentheses
elif len(stack) > 0 :
temp = stack.pop()
if rule.get(temp) != item:
return False
# if the item is right parentheses,
# and nothing left on the left
else:
return False
return True if len(stack) == 0 else FalseLast updated