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:
dir
subdir1
subdir2
file.ext
The directory dir
contains an empty sub-directory subdir1
and a sub-directory subdir2
containing a file file.ext
.
The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
represents:
dir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.ext
The directory dir
contains two sub-directories subdir1
and subdir2
. subdir1
contains a file file1.ext
and an empty second-level sub-directory subsubdir1
. subdir2
contains a second-level sub-directory subsubdir2
containing a file file2.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 is 32
(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, return 0
.
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)
where n
is the size of the input string.
Notice that a/aa/aaa/file1.txt
is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png
.
思路:stack存的是当前这一层level的path的长度;首先用\n split string,然后算总共有几个 \ t, 记住lastindexof是0 base的,所以要加1才是个数;while(stack.size() > level)这很巧妙的是,size = 1, level = 1,就不pop了,其实我回到了第二层,那么push进去就是第二层的长度;然后后面我生成path的时候,每次前面要加个 \ ,所有后面push length的时候,要+1;
class Solution {
public int lengthLongestPath(String input) {
if(input == null || input.length() == 0) {
return 0;
}
String[] splits = input.split("\n"); // 去掉\n;
// Stack 存的是当前这一个层的path的长度;
Stack<Integer> stack = new Stack<Integer>();
int maxlen = 0;
for(String word: splits) {
int level = word.lastIndexOf("\t") + 1; // lastIndexOf是0 based的,所以数量+1;
while(stack.size() > level) { // size = 1, level = 1, 相当于我回到第二层;
stack.pop();
}
int len = word.substring(level).length();
if(stack.isEmpty()) {
stack.push(len);
} else {
stack.push(stack.peek() + 1 + len); // add "\" + "file";
}
if(word.contains(".")) {
maxlen = Math.max(maxlen, stack.peek());
}
}
return maxlen;
}
}