Simple Python Solution


  • 0
    Y
    def isValid(self, s):
            if len(s)%2 != 0:
                return False
            stack = []
            for i,v in enumerate(s):
                if v == '(' or v == '{' or v == '[':
                    stack.append(v)
                elif len(stack) == 0:
                    pass
                elif (v == ')' and stack[-1] == '(') or (v == ']' and stack[-1] == '[') or (v == '}' and stack[-1] == '{'):
                        stack.pop()
            return not stack

  • 0
    J

    Hi, I have a small question, for line 8 and 9, which are
    elif len(stack) == 0:
    pass
    I don't quite get the usage of these two lines. Could you please help me a little bit? Thanks.


  • 0
    Y

    I think you are right. It doesn't make much sense.
    I changed "pass" to "return false"

    elif len(stack) == 0:
      return False
    

    previously I did pass because I wanted to avoid cases such as ")}{({))[{{[}" where at the beginning

    elif (v == ')' and stack[-1] == '(') or (v == ']' and stack[-1] == '[') or (v == '}' and stack[-1] == '{'):
    

    this would raise error because I used index -1 but there is nothing in the stack.
    then the loop will continue to run.
    If I change pass to return false, then the loop will terminate immediately, which would save some running time.

    Thanks for your question, which helped to improve my code quality.


Log in to reply
 

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