Python solution using stack - O(n) - 51ms


  • 4
    G
    class Solution:
        # @param s, a string
        # @return a boolean
        def isValid(self, s):
            paren_map = {
                '(': ')',
                '{': '}',
                '[': ']'
            }
            stack = []
    
            for p in s:
                if p in paren_map:
                    stack.append(paren_map[p])
                else:
                    if not stack or stack.pop() != p:
                        return False
    
            return not stack

  • 0
    L
    dic = {')':'(', ']':'[', '}':'{'}
            stack = [' ']
            for i in s:
                if i in '([{':
                    stack.append(i)
                elif dic.get(i, None) and dic.get(i, None) != stack.pop():
                    return False
            return stack == [' ']

  • 0

    Your

    elif dic.get(i, None) and dic.get(i, None) != stack.pop():
    

    can be replaced by just

    elif dic.get(i) != stack.pop():

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.