最长公共子串(Longest Common Substring)是指在多个字符串中找到的最长的连续相同字符序列。与最长公共子序列(Longest Common Subsequence)不同,公共子串要求字符必须连续。
下面是一个使用动态规划算法实现的Java代码示例:
public class LongestCommonSubstring {
public static String findLongestCommonSubstring(String[] strings) {
if (strings == null || strings.length == 0) {
return "";
}
String firstString = strings[0];
int n = firstString.length();
int m = strings.length;
String longestSubstring = "";
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
String substring = firstString.substring(i, j);
int k;
for (k = 1; k < m; k++) {
if (!strings[k].contains(substring)) {
break;
}
}
if (k == m && substring.length() > longestSubstring.length()) {
longestSubstring = substring;
}
}
}
return longestSubstring;
}
public static void main(String[] args) {
String[] strings = {"abcdef", "zabcf", "xabcdef"};
System.out.println("Longest Common Substring: " + findLongestCommonSubstring(strings));
}
}
最长公共子串是一个经典的字符串处理问题,可以通过动态规划等算法高效解决。在实际应用中,可以根据具体需求选择合适的算法实现。
领取专属 10元无门槛券
手把手带您无忧上云