388. Longest Absolute File Path
dir
subdir1
subdir2
file.extdir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.extLast updated
Was this helpful?
dir
subdir1
subdir2
file.extdir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.extLast updated
Was this helpful?
Was this helpful?
class Solution {
public int lengthLongestPath(String input) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(0); // "dummy" length
int maxLen = 0;
for(String s:input.split("\n")){
int lev = s.lastIndexOf("\t")+1; // number of "\t"
// System.out.println("s: "+ s + ", lev: " + lev + ", stack.size(): " + stack.size());
while(lev+1<stack.size()) stack.pop(); // find parent
int len = stack.peek()+s.length()-lev+1; // remove "/t", add"/"
// System.out.println("len: " + len);
stack.push(len);
// check if it is file
if(s.contains(".")) maxLen = Math.max(maxLen, len-1);
}
return maxLen;
}
}class Solution {
public int lengthLongestPath(String input) {
String[] paths = input.split("\n");
int[] stack = new int[paths.length+1];
int maxLen = 0;
for(String s:paths){
int lev = s.lastIndexOf("\t")+1, curLen = stack[lev+1] = stack[lev]+s.length()-lev+1;
if(s.contains(".")) maxLen = Math.max(maxLen, curLen-1);
}
return maxLen;
}
}