Python solution. Pythonic and fast.


  • 2
    P

    Decided to post my solution here, since most Python solutions I've seen here are not pythonic,
    which renderes using Python over Java/C++ pretty pointless.

    class Solution(object):
        def isValid(self, s):
            stack = []
            match = {'(': ')', '[': ']', '{': '}'}
            for c in s:
                if c in ['(', '[', '{']:
                    stack.append(c)
                elif not stack or match[stack.pop()] != c:
                    return False
            return not stack
    

  • 2

    Instead of if c in ['(', '[', '{'] I'd do if c in '([{' or if c in match.


  • 0
    P

    @StefanPochmann

    thanks for the reply. seems better with your way indeed!


Log in to reply
 

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