Simple Java Solution


  • 0
    D
    public int lengthLongestPath(String input) {
            int res = 0;
            Map<Integer, Integer> map = new HashMap<>();
            map.put(0, 0);
            String[] strs = input.split("\n");
            for (String s : strs) {
                int lvl = s.lastIndexOf("\t") + 1;
                int len = s.substring(lvl).length();
                if (s.contains(".")) {
                    res = Math.max(res, map.get(lvl) + len);
                    // if s contains '.'. It means this is the end. So just add the length
                }
                else {
                    map.put(lvl + 1, map.get(lvl) + len + 1); 
                    // 1 is for '/' in "dir/a.txt"
                }
            }
            return res;
        }

Log in to reply
 

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