39ms Python solution with explanation using stack

  • 0

    def lengthLongestPath(self, input):
    :type input: str
    :rtype: int
    dir_parts = input.split("\n")
    stack = []
    max_len = 0
    for dir in dir_parts:
    dirname = dir.strip("\t")
    num_of_tab = len(dir)-len(dirname)
    while num_of_tab < len(stack): #If the number of "\t" is less than the number of element(namely number of dirs) in stack, dir can not be appended to the current file path.
    stack.append(len(dirname)) #Push the length of dir or file onto stack
    if "." in dir:
    max_len = max(max_len,sum(stack)+len(stack)-1) #The file path equals the sum of length of all subdir plus the concatenation mark "/"
    return max_len

Log in to reply

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