如何提高此方法的性能以获得路径之间的相对路径?

时间:2015-11-02 17:25:27

标签: java performance indexing data-structures path

输入: fromPath - > “/ A / B / C”   toPath - > “A / B / d / F”

输出 relativePath - > “/../../ d / F

    public static String getRelativePath(String from, String to) {
    String relative = "";
    String regexPath = "/";
    String regexLow = "..";

    List<String> toList = Arrays.asList(to.split(regexPath));
    List<String> fromList = Arrays.asList(from.split(regexPath));

    int toSize = toList.size();
    int fromSize = fromList.size();

    relative += regexPath;

    for(int index = 0; index < fromSize; index++) {
        if(index <= toSize-1) {
            String toValue = toList.get(index);
            String fromValue = fromList.get(index);

            if(toValue.equals(fromValue)) {
                relative += regexLow + regexPath;
            }
            else
                relative += fromValue + regexPath;
        }
        else {
            if(index != fromSize-1)
                relative += fromList.get(index) + regexPath;
            else
                relative += fromList.get(index);
        }
    }

    return relative;
}

有更好的方法来优化/执行此代码吗?从嵌套循环开始,然后直接使用索引。

0 个答案:

没有答案