您可以对所有路径进行标记化,循环遍历每条路径,并针对每条路径循环遍历其他路径.
只需在索引1处比较它们,然后向右搜索,直到它们不再匹配.将路径存储在集合内.
根据您想要的输出,您需要为前几部分中的每一部分提供一条公共路径,即partA
、partD
、partG
和partJ
.
import java.util.*;
import java.util.stream.*;
public class LongestCommonPath {
public static void main(String[] args) {
String arr[] = {
"/partA/partB/partC/value1", "/partA/partB/partC/value2",
"/partD/partE/partF/value1", "/partD/partE/partF/value2",
"/partG/partH/partI/value1", "/partG/value2",
"/partJ/value1"
};
for (String path : longestCommonPaths(1, "/", arr)) {
System.out.println(path);
}
}
public static List<String> longestCommonPaths(int offset, String delimiter, String... paths) {
Set<String> result = new LinkedHashSet<>();
List<List<String>> tokenizedPaths = Stream.of(paths).map(path -> tokenizePath(path, delimiter)).collect(Collectors.toList());
for (List<String> currPath : tokenizedPaths) {
boolean found = false;
for (List<String> otherPath : tokenizedPaths) {
if (currPath != otherPath && currPath.get(offset).equals(otherPath.get(offset))) {
result.add(commonPath(currPath, otherPath).stream().collect(Collectors.joining(delimiter)));
found = true;
}
}
if (!found) {
result.add(currPath.stream().collect(Collectors.joining(delimiter)));
found = false;
}
}
return new ArrayList<>(result);
}
private static List<String> commonPath(List<String> path, List<String> otherPath) {
int index = 0;
while (index < path.size() && index < otherPath.size() && path.get(index).equals(otherPath.get(index))) {
index++;
}
return path.subList(0, index);
}
private static List<String> tokenizePath(String path, String delimiter) {
return Stream.of(path.split(delimiter)).collect(Collectors.toList());
}
}
输出
/partA/partB/partC
/partD/partE/partF
/partG
/partJ/value1