Skip to content

Instantly share code, notes, and snippets.

@senthil1216
Created March 1, 2018 07:38
Show Gist options
  • Save senthil1216/6f2b325fc548bee0a4f6632e3b5d84d4 to your computer and use it in GitHub Desktop.
Save senthil1216/6f2b325fc548bee0a4f6632e3b5d84d4 to your computer and use it in GitHub Desktop.
Longest Absolute file path
// https://leetcode.com/problems/longest-absolute-file-path/description/
class Solution {
class FileLevel {
int level; int len;
}
public int countOfCharacter(String s, Character seq){
int count = 0;
for(int i = 0 ;i < s.length();i++){
if(s.charAt(i) == seq){
count += 1;
} else {
return count;
}
}
return count;
}
public int lengthLongestPath(String input) {
String[] tokens = input.split("\n");
Stack<FileLevel> levelStack = new Stack<FileLevel>();
int maxLen = 0;
for(String token: tokens){
int level = countOfCharacter(token, '\t');
if(token.contains(".")){
while(!levelStack.empty() && level <= levelStack.peek().level){
levelStack.pop();
}
int prevLevel = levelStack.empty() ? 0 : levelStack.peek().len;
maxLen = Math.max(maxLen, prevLevel + token.length() - level);
} else {
while(!levelStack.empty() && level <= levelStack.peek().level){
levelStack.pop();
}
FileLevel fl = new FileLevel();
int prevLen = levelStack.empty() ? 0 : levelStack.peek().len;
fl.len = prevLen + token.length() + 1 - level; // .. +1 is for the trailing `/` character sequence
fl.level = level;
levelStack.push(fl);
}
}
return maxLen;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment