Advertisement
Guest User

solution to longest absolute path

a guest
Feb 24th, 2020
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. test_1 = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
  2.  
  3.  
  4. def lengthLongestPath(string):
  5.   # a stack, each element is a tuple ("dir_name", length of name)
  6.   pwd = []
  7.   prefix_length = 0
  8.   currMax = -1
  9.   # if we see \n means we go into the next directory
  10.   # the number of \t s folllowing \n is the number of elements in pwd we need to keep
  11.   items = string.split("\n")
  12.   for i in items:
  13.     tab_split = i.split("\t")
  14.     # length of tab_split - 1 is the no of elem we want to keep in pwd
  15.     while (len(pwd) > len(tab_split) -1): # remove excess items
  16.       prefix_length -= pwd.pop()[1] # index 1 is the length
  17.     curr_item = tab_split[-1]
  18.     # cannot find dot, is a directory
  19.     if not curr_item.find('.'):
  20.       pwd += (curr_item, len(curr_item))
  21.     else: # current item is a file
  22.       # length of current path = filename_len + prefix_length + no of slashes
  23.       currMax = max(currMax, len(curr_item) + prefix_length + len(pwd))
  24.     return currMax
  25.  
  26. lengthLongestPath(test_1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement