输入: 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;
}
有更好的方法来优化/执行此代码吗?从嵌套循环开始,然后直接使用索引。