|
| 1 | +/** |
| 2 | + * 388. Longest Absolute File Path |
| 3 | + * https://leetcode.com/problems/longest-absolute-file-path/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Suppose we have a file system that stores both files and directories. An example of one system |
| 7 | + * is represented in the following picture: |
| 8 | + * |
| 9 | + * Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 |
| 10 | + * and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains |
| 11 | + * a subdirectory subsubdir2, which contains a file file2.ext. |
| 12 | + * In text form, it looks like this (with ⟶ representing the tab character): |
| 13 | + * |
| 14 | + * dir |
| 15 | + * ⟶ subdir1 |
| 16 | + * ⟶ ⟶ file1.ext |
| 17 | + * ⟶ ⟶ subsubdir1 |
| 18 | + * ⟶ subdir2 |
| 19 | + * ⟶ ⟶ subsubdir2 |
| 20 | + * ⟶ ⟶ ⟶ file2.ext |
| 21 | + * |
| 22 | + * If we were to write this representation in code, it will look like this: |
| 23 | + * "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext". |
| 24 | + * Note that the '\n' and '\t' are the new-line and tab characters. |
| 25 | + * |
| 26 | + * Every file and directory has a unique absolute path in the file system, which is the order of |
| 27 | + * directories that must be opened to reach the file/directory itself, all concatenated by '/'s. |
| 28 | + * Using the above example, the absolute path to file2.ext is "dir/subdir2/subsubdir2/file2.ext". |
| 29 | + * Each directory name consists of letters, digits, and/or spaces. Each file name is of the form |
| 30 | + * name.extension, where name and extension consist of letters, digits, and/or spaces. |
| 31 | + * |
| 32 | + * Given a string input representing the file system in the explained format, return the length of |
| 33 | + * the longest absolute path to a file in the abstracted file system. If there is no file in the |
| 34 | + * system, return 0. |
| 35 | + * |
| 36 | + * Note that the testcases are generated such that the file system is valid and no file or directory |
| 37 | + * name has length 0. |
| 38 | + */ |
| 39 | + |
| 40 | +/** |
| 41 | + * @param {string} input |
| 42 | + * @return {number} |
| 43 | + */ |
| 44 | +var lengthLongestPath = function(input) { |
| 45 | + const stack = [0]; |
| 46 | + let result = 0; |
| 47 | + |
| 48 | + for (const line of input.split('\n')) { |
| 49 | + const level = line.lastIndexOf('\t') + 1; |
| 50 | + while (stack.length > level + 1) stack.pop(); |
| 51 | + stack.push(stack.at(-1) + line.length - level + 1); |
| 52 | + if (line.includes('.')) { |
| 53 | + result = Math.max(result, stack.at(-1) - 1); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return result; |
| 58 | +}; |
0 commit comments