Leetcode 388. Longest Absolute File Path
You are given a string representation of a file system in which different levels of directories and files are separated by newline (\n
) characters and where each level is indicated by a number of tab (\t
) characters.
For example, a string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
represents a file system such that:
dir
subdir1
subdir2
file.ext
Here, the longest absolute path to a file is "dir/subdir2/file.ext"
, and its length is 20 (note that the forward slashes are not counted as separators between directories and files).
Write a program that finds the length of the longest absolute path to a file in the given string representation of the file system. If there is no file in the system, return 0.
.
) character which implies it is a file; otherwise, it is a directory.\n
) to split the string into different components representing files and directories.\t
) to determine the depth level of each component. The number of \t
characters directly relates to the depth of the file or directory.#include <iostream>
#include <sstream>
#include <vector>
#include <stack>
#include <algorithm>
int lengthLongestPath(const std::string &input) {
std::istringstream ss(input);
std::string line;
std::stack<int> pathStack;
int maxLength = 0;
while (std::getline(ss, line)) {
size_t numTabs = line.find_first_not_of("\t");
int level = numTabs;
std::string name = line.substr(numTabs);
while (pathStack.size() > level) {
pathStack.pop();
}
int currLength = name.size() + (pathStack.empty() ? 0 : pathStack.top() + 1); // +1 for '/' between dirs/files
if (name.find('.') != std::string::npos) {
maxLength = std::max(maxLength, currLength);
} else {
pathStack.push(currLength);
}
}
return maxLength;
}
int main() {
std::string input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext";
std::cout << "The longest path length is: " << lengthLongestPath(input) << std::endl;
return 0;
}
n
is the length of the input string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?