Longest Absolute File Path using java


  • 0
    L
    public static int lengthLongestPath(String input) {
            List<String> paths = new ArrayList<>();
            String[] strs = input.split("\\n");
            dfs(strs, 0, 0, "", paths);
            if (paths.size() > 0) {
                System.out.println(paths);
                return paths.get(paths.size() - 1).length() - 1;
            }
            return 0;
        }
    
        public static int dfs(String[] strs, int i, int deep, String path, List<String> res) {
            String preDic = "";
            while (i < strs.length) {
                String str = strs[i];
                int j = 0;
                while (str.startsWith("\t")) {
                    str = str.substring(1);
                    j++;
                }
                if (j == deep) {
                    if (str.contains(".")) {
                        String pathTemp = path + "/" + str;
                        if (res.size() > 0) {
                            if (res.get(0).length() < pathTemp.length()) {
                                res.clear();
                                res.add(pathTemp);
                            } else if (res.get(0).length() == pathTemp.length()) {
                                res.add(pathTemp);
                            }
                        } else {
                            res.add(pathTemp);
                        }
                    } else {
                        preDic = str;
                    }
                    i++;
                } else if (j > deep) {
                    if (preDic.length() > 0) {
                        i = dfs(strs, i, deep + 1, path + "/" + preDic, res);
                    } else {
                        i = dfs(strs, i, deep + 1, path, res);
                    }
                } else {
                    return i;
                }
            }
            return i;
        }
    

Log in to reply
 

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