12 lines simple Python using stack with explanation.

  • 0

    Here "level" means how deep the current level, "pre" means the last "level". And we use a stack called "paths" to record lengths of each step in current path.
    If "level" is no bigger than "pre", it means we are in a new file path, we need to pop the corresponding steps from previous path. Each time we find "." in current step, we calculate the maximum length.

    class Solution(object):
        def lengthLongestPath(self, input):
            :type input: str
            :rtype: int
            paths = []
            ans, pre = 0, -1
            for step in input.split("\n"):
                path = len(step.lstrip("\t"))
                level = len(step) - path
                for _ in range(pre-level+1):
                if "." in step:
                    ans = max(ans, sum(paths) - 1)
                pre = level
            return ans

Log in to reply

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