3ms, Java Solution


  • 0
    Y
        public int lengthLongestPath(String input) {
            Stack<Integer> stack = new Stack();
            int len = 0;
            int level = 0;
            boolean isFile = false;
            int max = 0;
            char[] chars = input.toCharArray();
            for(char c : chars) {
                switch(c) {
                    case '\t':
                        level++;
                        break;
                    case '\n':
                        while(stack.size() > level) stack.pop();
                        len = stack.isEmpty() ? len : stack.peek() + len;
                        if (isFile) max = Math.max(max, len);
                        else stack.push(len + 1);
                        
                        isFile = false;
                        level = 0;
                        len = 0;
                        break;
                    case '.':
                        isFile = true;
                    default:
                        len++;
                }
            }
            if(isFile) {
                while(stack.size() > level) stack.pop();
                len = stack.isEmpty() ? len : stack.peek() + len;
                max = Math.max(max, len);
            }
            return max;
        }
    

Log in to reply
 

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