20. Valid Parentheses

Given a string s containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.


Note: Remember to think what happens with remaining items on stack?


def isValid(s: str):
       
    stack = []
    pairs = {')': '(', '}': '{', ']': '['}
   
    for c in s:
        if c in pairs.values():
            stack.append(c)
        else:
            if not stack or (stack[-1] != pairs[c]):
                return False                                    
            stack.pop()
           
    return not stack

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break