Java Solution


  • 0
    A
    class Solution {
        public int lengthLongestPath(String input) {
            int longest = 0;
            Stack<Integer> s = new Stack<Integer>();
            if (input == null || input.length() == 0) {
                return 0;
            }
            int pos = 0;
            while (pos < input.length()) {
                int index = input.indexOf("\n", pos);
                if (index == -1) {
                    index = input.length();
                }
                String name = input.substring(pos, index);
                int ntabs = 0;
                for (; name.charAt(ntabs) == '\t'; ntabs++);
                int nameLen = index - pos - ntabs;
                while (s.size() > ntabs) {
                    s.pop();
                }
                int currLen = nameLen;
                if (!s.isEmpty()) {
                    currLen += s.peek();
                }
                if (name.indexOf('.') == -1) { // is a dir
                    s.push(currLen + 1);
                } else {
                    
                    if (longest < currLen) {
                        longest = currLen;
                    }
                }
                if (index == input.length()) {
                    break;
                } else {
                    pos = index + 1;
                }
            }
            return longest;
        }
    }
    

Log in to reply
 

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