Loading

388. [栈]文件的最长绝对路径

388. 文件的最长绝对路径

以示例 "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" ,我们肯定会使用 String.split("\n") 分割字符串,会得到 {dir, \tsubdir1, \tsubdir2, \tfile.ext}

利用字符串前面'\t'的个数来当前目录或文件在第几层。第一层0个,第二层就有一个\t ... 以此类推。

利用一个栈记录前面几层的字符串长度,当遍历时遇到 "." 时,说明计算到文件名了,更新结果,继续计算。

class Solution {
    public int lengthLongestPath(String input) {
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        int ans = 0;
        // 以 \n 分割成字符串数组
        String[] str = input.split("\n");
        // dir,\tsubdir1,\tsubdir2,\tfile.ext
        for (String s : str) {
            // level 代表当前字符串的首字母索引
            // 字符串前面可能会有多个\t,故使用 lastIndexOf 找出最后一个 \t 位置即可
            int level = s.lastIndexOf("\t") + 1;
            while (level + 1 < stack.size()) {
                stack.pop();
            }
            // 之前入栈的字符串 + 当前遍历到的字符串的长度
            int len = stack.peek() + (s.length() - level + 1);
            stack.push(len);
            if (s.contains(".")) {
                ans = Math.max(ans, len - 1);
            }
        }
        return ans;
    }
}
posted @ 2020-10-24 12:24  上海井盖王  阅读(59)  评论(0)    收藏  举报