|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(d), d is the max depth of the paths |
| 3 | + |
| 4 | +# Suppose we abstract our file system by a string in the following manner: |
| 5 | +# |
| 6 | +# The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: |
| 7 | +# |
| 8 | +# dir |
| 9 | +# subdir1 |
| 10 | +# subdir2 |
| 11 | +# file.ext |
| 12 | +# The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. |
| 13 | +# |
| 14 | +# The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents: |
| 15 | +# |
| 16 | +# dir |
| 17 | +# subdir1 |
| 18 | +# file1.ext |
| 19 | +# subsubdir1 |
| 20 | +# subdir2 |
| 21 | +# subsubdir2 |
| 22 | +# file2.ext |
| 23 | +# The directory dir contains two sub-directories subdir1 and subdir2. |
| 24 | +# subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. |
| 25 | +# subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext. |
| 26 | +# |
| 27 | +# We are interested in finding the longest (number of characters) absolute path to a file within our file system. |
| 28 | +# For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", |
| 29 | +# and its length is 32 (not including the double quotes). |
| 30 | +# |
| 31 | +# Given a string representing the file system in the above format, |
| 32 | +# return the length of the longest absolute path to file in the abstracted file system. |
| 33 | +# If there is no file in the system, return 0. |
| 34 | +# |
| 35 | +# Note: |
| 36 | +# The name of a file contains at least a . and an extension. |
| 37 | +# The name of a directory or sub-directory will not contain a .. |
| 38 | +# Time complexity required: O(n) where n is the size of the input string. |
| 39 | +# |
| 40 | +# Notice that a/aa/aaa/file1.txt is not the longest file path, if there is |
| 41 | +# another path aaaaaaaaaaaaaaaaaaaaa/sth.png. |
| 42 | + |
| 43 | + |
| 44 | +class Solution(object): |
| 45 | + def lengthLongestPath(self, input): |
| 46 | + """ |
| 47 | + :type input: str |
| 48 | + :rtype: int |
| 49 | + """ |
| 50 | + def split_iter(s, tok): |
| 51 | + start = 0 |
| 52 | + for i in xrange(len(s)): |
| 53 | + if s[i] == tok: |
| 54 | + yield s[start:i] |
| 55 | + start = i + 1 |
| 56 | + yield s[start:] |
| 57 | + |
| 58 | + |
| 59 | + max_len = 0 |
| 60 | + path_len = {0: 0} |
| 61 | + for line in split_iter(input, '\n'): |
| 62 | + name = line.lstrip('\t') |
| 63 | + depth = len(line) - len(name) |
| 64 | + if '.' in name: |
| 65 | + max_len = max(max_len, path_len[depth] + len(name)) |
| 66 | + else: |
| 67 | + path_len[depth + 1] = path_len[depth] + len(name) + 1 |
| 68 | + return max_len |
0 commit comments