描述
给出两个字符串,找到最长公共子串,并返回其长度。
样例
样例 1:
输入: "ABCD" and "CBCE"
输出: 2
解释:
最长公共子串是 "BC"
样例 2:
输入: "ABCD" and "EACB"
输出: 1
解释:
最长公共子串是 'A' 或 'C' 或 'B'
挑战
O(n x m) time and memory.
注意事项
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
代码部分
public class Solution {
/**
* @param A: A string
* @param B: A string
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here
if(A.length()==0||B.length()==0) return 0;
int[][] dp=new int[A.length()+1][B.length()+1]; //dp[i][j]表示A字符串匹配到i,B字符串匹配到j时的最大长度;
int maxLength=0;
for(int i=1;i<=A.length();i++){
for(int j=1;j<=B.length();j++){
if(A.charAt(i-1)==B.charAt(j-1)){
dp[i][j]=dp[i-1][j-1]+1;
}else{
dp[i][j]=0;
}
if(dp[i][j]>maxLength){
maxLength=dp[i][j];
}
}
}
return maxLength;
}
}
补充说明
分析:这是一个经典的动态规划题,定义dp矩阵,dp[i][j]表示A串匹配到i,B串匹配到j时的最大公共长度。 dp有A.length()+1行,有B.length()列。第一行与第一列都为0;
有状态转移方程
dp[i][j]=dp[i-1][j-1]+1 ,A[i]==B[j]
dp[i][j]=0 ,A[i]!=B[j]
最后返回dp的最大值即为最长公共子串长度。
参照博客:https://blog.csdn.net/qq_27139155/article/details/79745323