给定一个长度相同且没有特殊字符的字符串列表:
List<String> myStringArray = List.of( "xxxyyyjjjabcdefg", xxxyyyjjjabcdefg", "xxxyyyxxxabcdefg")
;
我可以找到列表中最长的公共子串:
String lengthOfAllStrings = myStringArray.stream().min(Comparator.comparingInt(String::length)).get();
List<char[]> myCharArray = myStringArray.stream().map(String::toCharArray).collect(Collectors.toList());
StringBuilder longestCommonSubString = StringBuilder();
StringBuilder currentLongestSubString = new StringBuilder();
for(int i = 0; i < lengthOfAllStrings.length(); i++) {
int finalI = i;
if(myCharArray.stream().anyMatch((a) -> a[finalI] == ( (myCharArray.stream().collect(Collectors.groupingBy(x -> x[finalI]))).values().size == 1 ? (myCharArray.stream().collect(Collectors.groupingBy(x -> x[finalI]))).entrySet().iterator().next().getKey() : '!'))) {
longestCommonSubString.append((myCharArray.stream().collect(Collectors.groupingBy( x -> x[finalI]))).entrySet().iterator().next().getKey());
} else {
currentLongestSubString.append(longestCommonSubString);
longestCommonSubString = new StringBuilder();
}
}
System.out.println("The Longest Common Sub String = " + Stream.of(longestCommonSubString.toString(), currentLongestSubString.toString()).max(Comparator.comparingInt(String::length)).get());
输出:最长公共子字符串 = abcdefg
但是如果列表包含不同长度的字符串怎么办:
List<String> myStringArray = List.of( "xxxyyy", xxxyyy", "yyy");
所需输出:最长的子字符串 = yyy
另外,有没有一种方法可以用一个衬垫完成所有这些而不使用 for 循环?
你可以试试这个:
import java.util.*;
public class LongestCommonSubstring {
public static String findLongestCommonSubstring(List<String> strings) {
if (strings == null || strings.isEmpty()) {
return "";
}
String firstString = strings.get(0);
int maxLength = firstString.length();
String longestCommonSubstring = "";
for (int i = 0; i < maxLength; i++) {
for (int j = i + 1; j <= maxLength; j++) {
String substring = firstString.substring(i, j);
boolean isCommon = strings.stream().allMatch(s -> s.contains(substring));
if (isCommon && substring.length() > longestCommonSubstring.length()) {
longestCommonSubstring = substring;
}
}
}
return longestCommonSubstring;
}
public static void main(String[] args) {
List<String> myStringArray = List.of("xxxyyy", "xxxyyy", "yyy");
String longestCommonSubstring = findLongestCommonSubstring(myStringArray);
System.out.println("The Longest Common Substring = " + longestCommonSubstring);
}
}
此代码适用于不同长度的字符串列表,并将找到其中最长的公共子字符串。
对于使用单行而不使用 for 循环来完成此操作,这是不切实际的,因为在不同长度的字符串中查找最长的公共子串通常需要比较所有可能的子字符串,而使用单行或没有一些子串无法有效地完成此操作。迭代的形式。希望这可以帮助:)