Clear And Easy-To-Understand Java Solution Using Stack


  • 0
    D
    public class Solution {
        public int lengthLongestPath(String input) {
            if (input == null || input.isEmpty()) {
                return 0;
            }
            int currentLen = 0;
            int maxLen = 0;
            Stack<String> stack = new Stack<>();
            String[] lines = input.split("\n");
            int len = lines.length;
            for (int i = 0; i < len; i++) {
                // We need to assume that each dir or file is as "/XXXXX"
                while(!stack.isEmpty() && numberOfTab(lines[i]) <= numberOfTab(stack.peek())) {
                    currentLen -= (stack.peek().length() - numberOfTab(stack.peek()) + 1);
                    stack.pop();
                }
                currentLen += (lines[i].length() - numberOfTab(lines[i]) + 1);
                stack.push(lines[i]);
                if (isFile(lines[i])) {
                    maxLen = Math.max(maxLen, currentLen);
                }
            }
            // we need to remove the "/" at the very front
            return maxLen > 0 ? maxLen - 1 : 0;
        }
        
        public int numberOfTab(String str) {
            int num = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '\t') {
                    num += 1;
                }
            }
            return num;
        }
        
        public boolean isFile(String str) {
            return str.contains(".");
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.