Java solution with stack 4ms


  • 0
    V
    public class Solution {
      public int lengthLongestPath(String input) {
        input += '\n';
        List<Integer> stack = new ArrayList<Integer>();
        int max = 0, levelLen = 0, level = 0;
        boolean metDot = false;
        for (int i = 0; i < input.length(); i++) {
          char c = input.charAt(i);
          if (c == '\n') {
            while (stack.size() <= level) {
              stack.add(0);
            }
            int pathLen = (level == 0 ? 0 : stack.get(level - 1)) + levelLen;
            if (metDot) {
              if (pathLen > max) {
                max = pathLen;
              }
              metDot = false;
            } else {
              stack.set(level, pathLen + 1);
            }
            level = 0;
            levelLen = 0;
          } else if (c == '\t') {
            level++;
          } else {
            if (c == '.') {
              metDot = true;
            }
            levelLen++;
          }
        }
        return max;
      }
    }
    

Log in to reply
 

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