Share Simple Java Solution using Stack


  • 0
    M
            public int lengthLongestPath(String input) {
    		String[] d = input.split("\\n");
    		Stack<Integer> stack = new Stack<>();
    		int max = 0;
    		for (String s : d) {
    			int depth = 0;
    			while (s.charAt(depth) == '\t') {
    				++depth;
    			}
    			s = s.substring(depth);
    			while (!stack.isEmpty() && stack.size() > depth) stack.pop();			
    			int len = s.length();
    			if (!stack.isEmpty()) len += stack.peek() + 1;
    			if (s.contains(".")) {
    				max = Math.max(max, len);				
    			} else {
    				stack.push(len);
    			}
    		}
    		return max;
    	}
    

Log in to reply
 

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