🌕🌕 388. 文件的最长绝对路径

吞佛童子2022年10月10日
  • algorithm
  • String
  • HashMap
大约 2 分钟

🌕🌕 388. 文件的最长绝对路径

难度: 🌕🌕

问题描述

img_13.png


解法

class Solution {
    public int lengthLongestPath(String input) {
        // 思路:
        // 1. 不论是中间层的文件夹 还是 末尾层的文件 | 文件夹,以 '\n' 可以拆分
        // 2. '\t' 是制表符,这是一个字符
        // 3. 判断拆分后的子串,通过 '\t' 的数量可以判断出这是第几层的文件 | 文件夹
        // 若是文件,可以通过 前面几层保存的长度 + 当前层文件长度 获取结果
        // 若是文件夹,需要更新 当前层的长度
        if(!isFile(input)) {
            return 0;
        }
        // 包含文件
        int res = 0;
        String[] arr = input.split("\n");
        HashMap<Integer, Integer> map = new HashMap<>(); // 当前第几层[0 开始计算] - 前缀长度
        map.put(0, 0); // 第 0 级 的前缀长度为 0

        // 遍历
        for(String str: arr) {
            int count = getCurCount(str); // 获取当前层级

            // 是文件 - 更新 res
            if(isFile(str)) {
                int fileLen = str.length() - count; // 总长度 - '\t' 长度
                // 加上 文件前面的 '/'
                if(count != 0) {
                    fileLen ++;
                }
                // 获取当前层级的前缀长度
                int prevLen = map.get(count);
                res = Math.max(res, fileLen + prevLen);
            } else {
                // 说明是文件夹,更新 map
                int fileLen = str.length() - count;
                // 加上 '/' 前缀 - 第 0 层无需加前缀 '/'
                if(count != 0) {
                    fileLen ++;
                }
                int prevLen = map.get(count);
                // 更新下一层的前缀长度 - 即当前层包含前缀的总长度
                map.put(count + 1, fileLen + prevLen);
            }
        }
        return res;
    }

    private int getCurCount(String str) {
        // 获取当前是第几层,有一个 '\t' 增加一层
        int res = 0;
        int len = str.length();
        for(int i = 0; i < len; i ++) {
            if(str.charAt(i) == '\t') {
                res ++;
            } else {
                // '\t' 必定出现在前面,只要遇到不是 '\t' 说明后续肯定也不会有
                break;
            }
        }
        return res;
    }

    private boolean isFile(String str) {
        int len = str.length();
        int i = 0; // 定位 小数点 的位置
        for(; i < len; i ++) {
            if(str.charAt(i) == '.') {
                break;
            }
        }
        return i < len - 1; // 小数点不能是最后一位
    }
}

输出

img_12.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou