388. Longest Absolute File Path
use \t as level
use hashmap - simpler
T: O(n*L), n is number of string split by \n, L is each line's len
S: O(number of level)
class Solution {
public int lengthLongestPath(String input) {
int res = 0;
Map<Integer, Integer> map = new HashMap<>();
for (String s : input.split("\n")) {
int level = s.lastIndexOf("\t") + 1;
int len = s.substring(level).length();
map.put(0, 0); // 需要初始值(一開始 dir 要 .get(level) 無值), 不然就是之後 get 都要用 getOrDefault
if (s.contains(".")) {
res = Math.max(res, map.get(level) + len);
} else {
map.put(level + 1, map.get(level) + len + 1);
}
}
return res;
}
}
/*
return the length of the longest absolute path to a file in the abstracted file system
Input: input = "
split by \n, so the no \t means level 0, \t means level 1, \t\t means level2 (can seem as lastIndex+1)
String len = subtring(level).len\
m.put(level + 1, m.get(level) + len + 1); // 更新 len 到下一層(也就是會持續累加到下一層), +1 是 目錄斜線 (dir/subdir2/file.ext)
if (s.contains(".")) {
res = Math.max(res, m.get(level) + len); // 是 file 時 , 取出之前累加的len 加上目前 file 的 len
dir\n\
tsubdir1\n
\t\tfile1.ext\n // in . will cal the result, so in the following operarion, can replace data, it's ok
\t\tsubsubdir1\n
\tsubdir2\n
\t\tsubsubdir2\n
\t\t\tfile2.ext"
*/use array
Last updated
Was this helpful?