Java solution, easy to read


  • 0
    A
    public class Solution {
        public int lengthLongestPath(String input) {
            Stack<Integer> dirStack = new Stack<>();
            int idx = 0;
            int currPathLen = 0;
            int maxPathLen = 0;
            
            while (true) {
                if (idx >= input.length()) break;
                if (dirStack.size() > 0) currPathLen = dirStack.peek(); else currPathLen = 0;
                String dirOrFileName = getDirOrFileName(input, idx);
                idx += dirOrFileName.length();
                currPathLen += dirOrFileName.length();
                if (dirOrFileName.contains(".")) {
                    maxPathLen = Math.max(maxPathLen, currPathLen);
                } else {
                    dirStack.push(++currPathLen);
                }
                
                if (input.length() <= idx) break;
                idx++; // skipping new line
                int tabs = countTabs(input, idx);
                while (dirStack.size() > tabs) dirStack.pop();
                idx += tabs;
            }
            
            return maxPathLen;
        }
        
        String getDirOrFileName(String input, int idx) {
            StringBuilder sb = new StringBuilder();
            while (idx <= input.length() - 1 && input.charAt(idx) != '\n') {
                sb.append(input.charAt(idx++));
            }
            return sb.toString();
        }
        
        int countTabs(String input, int idx) {
            int result = 0;
            while (idx <= input.length() - 1 && input.charAt(idx) == '\t') { idx ++; result++; }
            return result;
        }
    }
    

Log in to reply
 

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