Java solution using stack with explaination


  • 0
    C
    public int lengthLongestPath(String input) {
            // stack is used to maintain count based on file depth
    		Stack<int[]> stack = new Stack<int[]>();
    		
    		int tabCount = 0, maxLength = 0;
    		boolean isFile = false, expectingFirstLetter = true;
    
    		for (int i = 0; i < input.length(); i++) {
    			char ch = input.charAt(i);
    
    			if (ch == '\t') {
    				tabCount++;
    			} 
    			else if (ch == '\n') {
    			    // if last parsed section was a file, time to compute max length
    				if (isFile) {
    					maxLength = Math.max(maxLength, stack.peek()[0]);
    					isFile = false;
    				}
    
    				tabCount = 0;
    				expectingFirstLetter = true;
    			} 
    			else {
    				if (expectingFirstLetter) {
    				    // adjusting length count based on the new tab count
    					while (!stack.isEmpty() && tabCount <= stack.peek()[1]) {
    						stack.pop();
    					}
    
    					expectingFirstLetter = false;
    					stack.push(new int[] { stack.isEmpty() ? 0 : stack.peek()[0] + 1, tabCount }); // added 1 to consider '/'
    				}
    
    				if (ch == '.') {
    					isFile = true;
    				}
    
    				stack.peek()[0]++;
    			}
    		}
    
            // handels use case when there is no \n or input ends at a file
    		if (!expectingFirstLetter && isFile) {
    			maxLength = Math.max(maxLength, stack.peek()[0]);
    		}
    
    		return maxLength;
        }
    

Log in to reply
 

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