AC python solution & easy to read


  • 0
    I
    class Solution(object):
        def isValid(self, code):
            """
            :type code: str
            :rtype: bool
            """
            stack=[]
            i=0
            firstMoodFlag=0
            maxStackDepth=0
            while i<len(code):
                if code[i]=='<':
                    i=i+1
                    
                    if i==len(code):
                        return False
                    if code[i].isupper():
                        firstMoodFlag+=1
                        j=i
                        while code[j]!='>':
                            if not code[j].isupper():
                                return False
                            j=j+1
                            if j==len(code):
                                return False
                        if len(code[i:j])<1 or len(code[i:j])>9:
                            return False
                        stack.append(code[i:j])
                        maxStackDepth=max(len(stack), maxStackDepth)
                        i=j+1
                        
                    elif code[i]=='/':
                        i=i+1
                        j=i
                        
                        while code[j]!='>':
                            if not code[j].isupper():
                                return False
                            j=j+1
                            if j==len(code):
                                return False
                        tagName=code[i: j]
                        if len(stack)==0 or tagName!=stack[-1]:
                            return False
                        else:
                            stack.pop()
                        
                        i=j+1
                    elif code[i]=='!':
                        cdata0, cdata1='[CDATA[',']]>'
                        j=i+1
                        track=0
                        while track<len(cdata0):
                            if cdata0[track].lower()!=code[j].lower():
                                return False
                            track=track+1
                            j=j+1
                            if j==len(code):
                                return False
                        while j< len(code)-3 and code[j:j+3]!=cdata1:
                            j=j+1
                        i=j+1
                    else:
                        return False
                else:
                    if len(stack)==0:
                        return False
                    i=i+1
            if firstMoodFlag>1 and maxStackDepth==1:
                return False
        
            return True if(len(stack)==0 and firstMoodFlag>=1)else False
    

Log in to reply
 

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