Suppose we have a file system that stores both files and directories.
If we were to write this representation in code, it will look like this: "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
. Note that the '\n'
and '\t'
are the new-line and tab characters.
Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s
. Using the above example, the absolute path to file2.ext
is "dir/subdir2/subsubdir2/file2.ext"
. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension
, where name
and extension
consist of letters, digits, and/or spaces.
Given a string input
representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0
.
Example:
Input: input = "file1.txt\nfile2.txt\nlongfile.txt"
Output: 12
Explanation: There are 3 files at the root directory.
Since the absolute path for anything at the root directory is just the name itself, the answer is "longfile.txt" with length 12.
Approach:
C++
#include <bits/stdc++.h>using namespace std;int lengthLongestPath(string input){stringstream ss(input);string line;unordered_map<int, int> map = {{0, 0}};int res = 0;while (getline(ss, line, '\n')){auto tab = line.find_last_of('\t');int level = tab == string::npos ? 0 : tab + 1;int len = line.substr(level).length();if (line.find('.') != string::npos){res = max(res, map[level] + len);}else{map[level + 1] = map[level] + len + 1;}}return res;}int main(){string input = "file1.txt\nfile2.txt\nlongfile.txt";cout << lengthLongestPath(input);return 0;}
No comments:
Post a Comment