Longest Absolute File Path

medium string stack dfs

Problem

Given a string representing the file system encoded with '\n' (newline) and '\t' (tab) to indicate depth, return the length of the longest absolute path to a file (including '/' separators). If no file exists, return 0.

Input"dir\n\tsub1\n\t\tfile1.ext\n\tsub2\n\t\tfile2"
Output18
"dir/sub1/file1.ext" has length 18.

def length_longest_path(s):
    best = 0
    lengths = {0: 0}
    for line in s.split('\n'):
        name = line.lstrip('\t')
        depth = len(line) - len(name)
        if '.' in name:
            best = max(best, lengths[depth] + len(name))
        else:
            lengths[depth + 1] = lengths[depth] + len(name) + 1
    return best
function lengthLongestPath(s) {
  let best = 0;
  const lengths = { 0: 0 };
  for (const line of s.split('\n')) {
    const name = line.replace(/^\t+/, '');
    const depth = line.length - name.length;
    if (name.includes('.')) {
      best = Math.max(best, lengths[depth] + name.length);
    } else {
      lengths[depth + 1] = lengths[depth] + name.length + 1;
    }
  }
  return best;
}
class Solution {
    public int lengthLongestPath(String input) {
        int best = 0;
        Map<Integer, Integer> lengths = new HashMap<>();
        lengths.put(0, 0);
        for (String line : input.split("\n")) {
            String name = line.replaceAll("^\\t+", "");
            int depth = line.length() - name.length();
            if (name.contains(".")) best = Math.max(best, lengths.get(depth) + name.length());
            else lengths.put(depth + 1, lengths.get(depth) + name.length() + 1);
        }
        return best;
    }
}
int lengthLongestPath(string s) {
    int best = 0;
    unordered_map<int, int> lengths; lengths[0] = 0;
    stringstream ss(s); string line;
    while (getline(ss, line, '\n')) {
        int depth = 0; while (depth < (int)line.size() && line[depth] == '\t') depth++;
        string name = line.substr(depth);
        if (name.find('.') != string::npos) best = max(best, lengths[depth] + (int)name.size());
        else lengths[depth + 1] = lengths[depth] + (int)name.size() + 1;
    }
    return best;
}
Time: O(n) Space: O(d) (max depth)