Java 函数:比较两个字符串的最大相同子字符串长度
下面是一个用动态规划算法实现的Java函数,用于比较两个字符串的最大相同子字符串长度:
public class Main {
public static int findMaxCommonSubstringLength(String str1, String str2) {
int[][] dp = new int[str1.length() + 1][str2.length() + 1];
int maxLength = 0;
for (int i = 1; i <= str1.length(); i++) {
for (int j = 1; j <= str2.length(); j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
maxLength = Math.max(maxLength, dp[i][j]);
}
}
}
return maxLength;
}
public static void main(String[] args) {
String str1 = "abcdxyz";
String str2 = "xyzabcd";
int maxLength = findMaxCommonSubstringLength(str1, str2);
System.out.println("最大相同子字符串长度: " + maxLength);
}
}
输出结果为:
最大相同子字符串长度: 4
在上面的例子中,字符串 "abcd" 和 "xyz" 是两个字符串的最大相同子字符串,长度为 4。
原文地址: https://www.cveoy.top/t/topic/qhyy 著作权归作者所有。请勿转载和采集!