求两个字符串的最长公共子串java
时间: 2023-08-09 14:08:17 浏览: 130
可以使用动态规划算法来求解两个字符串的最长公共子串,以下是Java实现示例:
```java
public static String findLongestCommonSubstring(String s1, String s2) {
int m = s1.length(), n = s2.length();
// 初始化二维数组
int[][] dp = new int[m + 1][n + 1];
int maxLen = 0, endPos = 0;
// 填充数组
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
if (dp[i][j] > maxLen) {
maxLen = dp[i][j];
endPos = i - 1;
}
} else {
dp[i][j] = 0;
}
}
}
return s1.substring(endPos - maxLen + 1, endPos + 1);
}
```
使用示例:
```java
String s1 = "abcdefg";
String s2 = "bcdefgh";
System.out.println(findLongestCommonSubstring(s1, s2)); // 输出 "bcdef"
```
阅读全文