一道新浪面试算法题,两行代码搞定,有兴趣的看看

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

新浪一道面试题:写一个函数,算出两个文件的相对路径的 递归算法

 

   public static void main(String[] args) throws Exception {

        String pathA = "/a/b/c/d/g/m/1.txt";
        String pathB = "/c/b/c/d/g/h/2.txt";
        System.out.println(pathARelativePathBRecursion(pathA,pathB,""));
    }

    /**
     * pathA相对于pathB的相对路径 递归算法:
     *
     * @param pathA
     * @param pathB
     * @param i
     * @return
     */
    public static String pathARelativePathBRecursion(String pathA,String pathB, String tempPath) {
        if (pathA.startsWith(pathB))
            return pathA.replaceFirst(pathB+"/",tempPath.substring(0,tempPath.length()-3));
        else
            return pathARelativePathBRecursion(pathA, pathB.substring(0, pathB.lastIndexOf("/")), "../" + tempPath);
    }

转载于:https://my.oschina.net/xianggao/blog/79343

你可能感兴趣的:(一道新浪面试算法题,两行代码搞定,有兴趣的看看)