Python stack solution O(n) time, 48 ms


  • 0
    Y
    class Solution(object):
        def lengthLongestPath(self, input):
            """
            :type input: str
            :rtype: int
            """
            strList = input.split("\n")
            if not strList: return 0
            lgthList = [0]
            maxL = 0
            levelp = -1
            for s in strList:
                leadingspace = True if s[0]==' ' else False
                j=0
                for i,c in enumerate(s):
                    j=i
                    if c<>' ': break
                if i>=4: s = s[4:]
                else: s = s.lstrip(' ')                         #remove leading whitespaces
                if leadingspace & (s[0]<>'\t'): s = '\t'+s      #Add the tab key
                level = s.count('\t')
                if level<=levelp:
                    while(level<=levelp):
                        lgthList.pop()
                        levelp -= 1
                levelp = level
                        
                lgthList.append( lgthList[-1]+len(s)-level+1 )
                if( (s.find('.')<>-1) & (lgthList[-1]>maxL) ): 
                    maxL = lgthList[-1]-1
    
            return maxL
    
    

Log in to reply
 

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