Short Python with stack


  • 0

    Here I use a stack calledacc to represent the current accumulative file names.

    First, we split input into parts by \n, and store the corresponding level and length as a tuple in list A. Then, every time we see . in a file name, we update ans with current stack acc.

    class Solution(object):
        def lengthLongestPath(self, input):
            """
            :type input: str
            :rtype: int
            """
            s = input.split("\n")
            A = [(len(x) - len(x.lstrip("\t")), len(x.lstrip("\t"))) for x in s]
            ans, acc = 0, []
            for i, x in enumerate(A):
                while acc and x[0] <= acc[-1][0]: acc.pop()
                acc.append(x)
                if "." in s[i]: ans = max(ans, sum(x[1] for x in acc) + acc[-1][0])
            return ans
    

Log in to reply
 

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