36ms python clear solution


  • 0
    Z
    class Solution(object):
        def isValid(self, s):
            """
            :type s: str;; rtype: bool
            """
            stack = []
            for p in s:
                if p in '[({': stack.append(p)
                else:
                    if not stack: return False
                    elif p == ']' and stack.pop() != '[':
                        return False
                    elif p == ')' and stack.pop() != '(':
                        return False
                    elif p == '}' and stack.pop() != '{':
                        return False
            return (stack == [])

  • 2
    J

    Here is my solution, I changed my last return based on your code. It can be cleared if you combine the stack.pop() and p.

       class Solution(object):
            def isValid(self, s):
                """
                :type s: str
                :rtype: bool
                """
                stack=[]
                for i in s:
                    if i in ['(','[','{']:
                        stack.append(i)
                    elif i in [')',']','}']:
                        if stack:
                            p=stack.pop()
                            if p+i not in ['()','[]','{}']:
                                return False
                        else:return False
                return (stack==[])

  • 0
    Z

    Thumbs up! Combining p and i before comparison is a good idea.


Log in to reply
 

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