L643 Longest Absolute File Path (388)
Suppose we abstract our file system by a string in the following manner:
The string"dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
represents:
The directorydir
contains an empty sub-directorysubdir1
and a sub-directorysubdir2
containing a filefile.ext
.
The string"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
represents:
The directorydir
contains two sub-directoriessubdir1
andsubdir2
.subdir1
contains a filefile1.ext
and an empty second-level sub-directorysubsubdir1
.subdir2
contains a second-level sub-directorysubsubdir2
containing a filefile2.ext
.
We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is"dir/subdir2/subsubdir2/file2.ext"
, and its length is32
(not including the double quotes).
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. If there is no file in the system, return0
.
Note:
The name of a file contains at least a
.
and an extension.The name of a directory or sub-directory will not contain a
.
.
Time complexity required:O(n)
wheren
is the size of the input string.
Notice thata/aa/aaa/file1.txt
is not the longest file path, if there is another pathaaaaaaaaaaaaaaaaaaaaa/sth.png
.
这题首先用split把每部分拆出来。然后要注意每一层跟stack size的关系。如果层数小于stack的size时,就pop。每次pop完,就push新的part。stack里为了节省计算时间,存的是prefix sum。prefix sum多开一位方便计算。所以一开始多push一个0.这里还巧妙得用到了lastIndexOf()。真心很久没写java,好虚。T:O(n), S:O(n)
下面是九章的答案,其实我们可以用一个数组代替stack。
Last updated