最长公共子串的长度 描述:给定两个字符串str1和str2,输出两个字符串的最长公共子串的长度(假设str1和str2的最长公共子串存在且唯一)。 输入样例: 1AB2345CD 12345EF 输出样例: 4 说明:最长的公共子串为2345;java
时间: 2024-05-23 16:10:55 浏览: 25
可以使用动态规划来解决这个问题。
设 $dp[i][j]$ 表示以 $str1[i]$ 和 $str2[j]$ 结尾的最长公共子串的长度。当 $str1[i]$ 和 $str2[j]$ 相等时,$dp[i][j]$ 可以转移为 $dp[i-1][j-1]+1$,否则 $dp[i][j]$ 为 0。最后取所有 $dp[i][j]$ 中的最大值即为最长公共子串的长度。
具体实现时,可以用一个变量 $maxLen$ 来记录最大值,每次更新 $dp[i][j]$ 时,如果 $dp[i][j]>maxLen$ 则更新 $maxLen$。
Java 代码如下:
相关问题
最长公共子串的长度 描述:给定两个字符串str1和str2,输出两个字符串的最长公共子串的长度(假设str1和str2的最长公共子串存在且唯一)。
最长公共子串问题可以使用动态规划求解。
定义一个二维数组dp,其中dp[i][j]表示以str1[i]和str2[j]结尾的最长公共子串的长度。如果str1[i]和str2[j]不相等,则dp[i][j]=0;如果相等,则有dp[i][j]=dp[i-1][j-1]+1。
最终的最长公共子串的长度就是dp数组中的最大值。
以下是Python代码实现:
```python
def longest_common_substring(str1, str2):
m, n = len(str1), len(str2)
dp = [[0] * n for _ in range(m)]
max_len = 0
for i in range(m):
for j in range(n):
if str1[i] == str2[j]:
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = dp[i-1][j-1] + 1
max_len = max(max_len, dp[i][j])
return max_len
```
例如,对于字符串"abcdefg"和"bcdeff",最长公共子串为"bcdef",长度为5。
用java实现:最长公共子串的长度 描述:给定两个字符串str1和str2,输出两个字符串的最长公共子串的长度(假设str1和str2的最长公共子串存在且唯一)。
以下是用Java实现最长公共子串长度的示例代码:
```java
public class LongestCommonSubstring {
public static int longestCommonSubstring(String str1, String str2) {
int m = str1.length();
int n = str2.length();
int maxLength = 0;
int[][] dp = new int[m+1][n+1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; 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 = longestCommonSubstring(str1, str2);
System.out.println("The length of longest common substring is " + maxLength);
}
}
```
以上代码使用动态规划算法来解决该问题。通过定义一个二维数组`dp`,其中`dp[i][j]`表示以`str1`的第`i`个字符和`str2`的第`j`个字符为结尾的最长公共子串的长度。当`str1.charAt(i-1) == str2.charAt(j-1)`时,表示`str1`和`str2`的第`i`和`j`个字符相同,因此可以通过`dp[i-1][j-1]`得到以`str1`的第`i-1`个字符和`str2`的第`j-1`个字符为结尾的最长公共子串长度,并加上当前相同的字符,即可得到以`str1`的第`i`个字符和`str2`的第`j`个字符为结尾的最长公共子串的长度。同时,需要记录每次更新的最大长度,并在遍历完成后返回该长度。