LeetCode – Longest Absolute File Path (Java)

https://leetcode.com/problems/longest-absolute-file-path/

Java Solution 1

class Node{
    int level;
    int len;
    public Node(int lev, int len){
        this.level = lev;
        this.len = len;
    }
}
 
public class Solution {
    public int lengthLongestPath(String input) {
        if(input==null||input.length()==0)
            return 0;
 
        int max=0;
 
        String[] arr = input.split("\n");
 
        Stack<Node> stack = new Stack<Node>();
 
        for(int i=0; i<arr.length; i++){
            String s = arr[i];
 
            int count=0;
            int j=0;
            while(j<s.length()-1){
            	//System.out.println("first " + s.substring(j, j+2));
                if(s.substring(j, j+1).equals("\t")){
 
                	j++;  
                    count++;
                }else{
                	break;
                }
            }
 
            while(!stack.isEmpty() && count <=stack.peek().level){
                stack.pop();
            }
 
            if(s.contains(".")){
                if(stack.isEmpty()){
                    max = Math.max(max, s.length()-count);
                }else{
                    max = Math.max(max, stack.peek().len+s.length()-count);
                }
            }else{
            	if(stack.isEmpty()){
            		stack.push(new Node(count, s.length()-count+1));
            	}else{
            		stack.push(new Node(count, stack.peek().len + s.length()-count+1));
            	}
            }
        }
 
        return max;
    }
}

Java Solution 2

public int lengthLongestPath(String input) {
    int result = 0;
    String[] arr = input.split("\n");
 
    Deque<Integer> stack = new ArrayDeque<>(); 
    stack.push(0);
 
    for(int i=0; i<arr.length; i++){
        int lastIdx = arr[i].lastIndexOf('\t');
        int level = lastIdx + 1;
        int len = arr[i].length() - level;
 
        while(level < stack.size()-1){
            stack.pop();
        }
 
        if(arr[i].contains(".")){
            result = Math.max(result, len + stack.peek());
        }else{
            stack.push(stack.peek() + len + 1);
        }
    }
 
    return result;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Saravana

    “t” is just a single character in JDK11, count can be optimized as

    int idx = token.lastIndexOf("t");
    int count = idx + 1;