LeetCode 388: Longest Absolute File Path Solution
Master LeetCode problem 388 (Longest Absolute File Path), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
388. Longest Absolute File Path
Problem Explanation
Explanation
To solve this problem, we can use a stack to keep track of the current directory level and their lengths. We iterate through the input string, keeping track of the current level of indentation (tabs) to determine the depth of the current file or directory. We update the stack accordingly while calculating the length of the absolute path to each file.
Algorithm:
- Split the input string by the newline character
\n. - Initialize a stack to keep track of directory lengths. Push 0 onto the stack for the root directory.
- Initialize a variable
maxLento store the maximum length found. - Iterate through each part of the split input string.
- Count the number of tabs to determine the level of indentation.
- Calculate the current length of the absolute path by adding the length of the current part and the length of the parent directory (obtained from the stack).
- If the current part represents a file, update
maxLenif the calculated length is greater. - If the current part represents a directory, update the stack with the current length for the new directory level.
- Return
maxLenas the result.
Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(n), for the stack.
Solution Code
class Solution {
public int lengthLongestPath(String input) {
Stack<Integer> stack = new Stack<>();
stack.push(0);
int maxLen = 0;
for (String s : input.split("\n")) {
int level = s.lastIndexOf("\t") + 1;
int len = stack.peek() + s.length() - level + 1;
while (level + 1 < stack.size()) {
stack.pop();
}
if (s.contains(".")) {
maxLen = Math.max(maxLen, len - 1);
} else {
stack.push(len);
}
}
return maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 388 (Longest Absolute File Path)?
This page provides optimized solutions for LeetCode problem 388 (Longest Absolute File Path) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 388 (Longest Absolute File Path)?
The time complexity for LeetCode 388 (Longest Absolute File Path) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 388 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 388 in Java, C++, or Python.