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

T:O(n*w), n is num of line, w is len of line, level is level num
S: O(n*w)
class Solution {
    public int lengthLongestPath(String input) {
        String[] data = input.split("\n"); // get each line string data
        String[] dir = new String[data.length];
        int res = 0;
        for (String s : data) { // for each line
            int level = s.lastIndexOf("\t") + 1; // get level
            
            dir[level] = s.substring(level, s.length()); // set data in level 
            int len = 0;
            
            if (dir[level].indexOf(".") != -1) { // if data is a file, cal the file path len
                for (int i = 0; i <= level;i++) { // add to that's level
                    len += dir[i].length();
                }
                len += level; // add level separator, "/"
            }
            res = Math.max(res, len); // find max file path len
        }
        return res;
    }
}

/*
1.  get each line string data by \n
dir\n
\tsubdir1\n
\tsubdir2\n
\t\tfile.ext

=>

dir
\tsubdir1
\tsubdir2
\t\tfile.ext

2. put data by \t num (means in which level) =>

[dir, subdir2, file.ext]

it's can be replaced


3. if data has "." , start to cal file path length 
dir[0] + / + dir[1] + / + dir[2]

4.
find max file path length 


T:O(n*w), n is num of line, w is len of line, level is level num
S: O(n*w)
*/

Last updated