Easy Java Solution using stack with explanation


  • 0
    D

    Algorithm:

    • split on \n
    • when I hit \t. I add on the stack before \n stack plus a count variable and len variable
    • if the number of \t is more then I add on stack add len to len variable
    • if less than I pop till the count does not become equal remove from len variable
    • if ends with .txt than I calculate the max length
    class Solution {
            public int lengthLongestPath(String input) {
    	        String []inputVals = input.split("\\n");
    	        Stack <Integer>st = new Stack();
    	        int count = 0;
    	        int len = 0;
    	        int maxLen = 0;
    	        for(int i=0;i<inputVals.length;i++){
    	            if(i==0){
    	                st.push(inputVals[0].length());//3
    	                len+=inputVals[0].length();//3
    	                count+=1;
                    if(inputVals[i].indexOf(".")!=-1)
    	                maxLen = Math.max(len-1+count,maxLen);
    	                continue;
    	            }
    	            int tab = countTabs(inputVals[i]);//2
    	            while(tab<count){
    	                int temp = st.pop();
    	                len -= temp;
    	                count--;
    	            }
    	            st.push(inputVals[i].length()-tab);//7
    	            len+=inputVals[i].length()-tab;//7
    	            count+=1;
    	            if(inputVals[i].indexOf(".")!=-1){
    	                maxLen = Math.max(len-1+count,maxLen);
    	            }
    	        }
    	        return maxLen;
    	    }
    	    
    	    int countTabs(String location){
    	        int c = 0;
    	        while(location.startsWith("\t")) {
    	        		location=location.substring(1);
    	        		c++;
    	        }
    	        return c;
    	    }
    }
    

Log in to reply
 

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