描述
给出两个字符串,找到最长公共子串,并返回其长度。
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
样例
给出A=“ABCD”,B=“CBCE”,返回 2
挑战
O(n x m) time and memory.
思路
这是一道动态规划题目,一开始没想到这方面,因为是字串而不是子序列。
后来手绘了一下下面这个例子,才想到了状态转移方程,这是一道动态规划题目。
C | B | C | E | |
A | 0 | 0 | 0 | 0 |
D | 0 | 0 | 0 | 0 |
B | 0 | 1 | 0 | 0 |
C | 1 | 0 | 2 | 0 |
状态转移方程是: 如果 A[i] = B[j],那么dp[i,j] = dp[i-1,j-1]+1。否则的话,dp[i,j] = 0。
然后这个矩阵中最大的那个数字就代表这最大的公共子串的大小了。
Java代码
public int longestCommonSubstring(String A, String B) {
// write your code here
if(A==null || B==null || A.length()==0 || B.length()==0){
return 0;
}
int[][] dp= new int[A.length()+1][B.length()+1];
int max = 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;
max = Math.max(max, dp[i][j]);
}
}
}
return max;
}