the solution that ran 32ms in python,a bit longer,but can reduce middle code's length


  • 0
    L
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            left=['[','{','(']
            right=['}',']',')']
            buff=[]
            count=-1
            if s[0] not in left:
                return False
            for i in range(len(s)):
                if s[i] not in right:
                    buff.append(s[i])
                    count+=1
                else:
                    if s[i]==')':
                        if count!=-1 and buff[count]=='(':
                            del(buff[count])
                            count-=1
                        else:
                            return False
                    elif s[i]==']':
                        if count!=-1 and buff[count]=='[':
                            del(buff[count])
                            count-=1
                        else:
                            return False
                    else:
                        if count!=-1 and buff[count]=='{':
                            del(buff[count])
                            count-=1
                        else:
                            return False
            if count!=-1:
                return False
            else:
                return True

Log in to reply
 

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