Problem
Suppose we abstract our file system by a string in the following manners:
The string
dir\n\tsubdir1\n\tsubdir2\n\t\tfile.extrepresents:dir subdir1 subdir2 file.exta directory
dircontains an empty sub-directoriessubdir1and a sub-directorysubdir2containing a filefile.ext.The string
dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.extrepresents:dir subdir1 file1.ext subsubdir1 subdir2 subsubdir2 file2.exta directory
dircontains two sub-directoriessubdir1andsubdir2.subdir1contains a filefile1.extandan empty second-level sub-directorysubsubdir1.subdir2contains a second-level sub-directorysubsubdir2containing a filefile2.ext.We are interested in finding the longest (number of characters) absolute path to a file within our file system. That is, for example, in the second example above, the longest absolute path is
dir/subdr2/subsubdir2/file.ext, and its length is 30.Given a string representing the file system in the above format, return the length of the longest absolute path to file in the abstracted file system. Simply put, that is the length of a valid path that ends with a file, and a file contains . and an extension.
Time complexity required: O(n) where n is the size of the input string.
Notice that
a/aa/aaa/file1.txtis not the path you want, if there isaaaaaaaaaaaaaaaaaaaaa/sth.png.
Any advice on code bugs, performance improvements in terms of algorithm time complexity, or code style advice is highly appreciated.
def find_longest_path(source): items = source.split('\n') prefix = [] prefix_length = [] max_length_so_far = -1 max_path_so_far = '' for path in items: i = 0 while path[i] == '\t': i += 1 if len(prefix) > i: prefix = prefix[:i] prefix_length = prefix_length[:i] prefix.append(path[i:]) prefix_length.append(len(path[i:])) if sum(prefix_length) > max_length_so_far: max_length_so_far = sum(prefix_length) max_path_so_far = '/'.join(prefix) return max_path_so_far if __name__ == "__main__": path_name = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" print find_longest_path(path_name) path_name = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" print find_longest_path(path_name)