Python solution with list simulating stack


  • 0
    Q
    class Solution:
    # @return a boolean
    def isValid(self, s):
        stack_s = ''
        for c in s:
            if c in {'(','{','['}:
                stack_s += c#push into stack directly
            elif c == ')':
                if stack_s and stack_s[-1] == '(':# if stack is not empty and the last element match input element
                    stack_s = stack_s[:-1]#then pop
                else:
                    return False
            elif c == ']':
                if stack_s and stack_s[-1] == '[':
                    stack_s = stack_s[:-1]
                else:
                    return False
            elif c == '}':
                if stack_s and stack_s[-1] == '{':
                    stack_s = stack_s[:-1]
                else:
                    return False
        if len(stack_s):#all the elements in s are used but stack is not empty, typically like s = '()[{', then False
            return False
        return True

Log in to reply
 

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