Stack with brief explanation. Java

  • 0

    By splitting by '\n' we splitte each dir or file. By splitting by '\t' we splitte by levels. We used stack to store path of directories. To know the level of current dirOrFile we need to count entrances of '\t' before dirOrFile. If level is higher than the stack size it means that it is inside stack's top dir. If level is less it means we processed dirs and files where level is higher than current level.

    public class Solution {
        public int lengthLongestPath(String input) {
            Stack<String> path = new Stack<>();
            String files[] = input.split("\n");
            int curLen = 0;
            int max = 0;
            for (String s: files) {
                String substr[] = s.split("\t");
                String dirOrFile = substr[substr.length-1];
                int level = substr.length;
                while (path.size()>=level) curLen -= path.pop().length();
                if (dirOrFile.contains(".")) {
                    max = Math.max(curLen + path.size() + dirOrFile.length(), max);
                } else {
            return max;

Log in to reply

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