題目描述
給出兩個字符串,找到最長公共子串,並返回其長度。
注意事項
子串的字符應該連續的出現在原字符串中,這與子序列有所不同。
樣例
給出A=“ABCD”,B=“CBCE”,返回 2
解題思路
應用動態規劃,狀態方程爲 dp[i][j]表示
dp[i][j] 表示 A[i-1] B[j-1] 字符結尾的最長公共子串,
動態轉移方程爲:
如果A[i-1] == B[j-1], 則 dp[i][j] = dp[i-1][j-1]+1
否則 dp[i][j] = 0
最後求Longest Common Substring的長度等於
max{ dp[i][j], 1<=i<=n, 1<=j<=m}
程序實現
public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
// LCS
public int longestCommonSubstring(String A, String B) {
if(A==null||A.length()==0||B==null||B.length()==0)
return 0;
char[] chA=A.toCharArray();
char[] chB=B.toCharArray();
int lenA=A.length();
int lenB=B.length();
int[][] dp=new int[lenA+1][lenB+1];
int maxLen=0;
//dp[i][j] 表示以 A[i-1] B[j-1] 結尾的公共子串長度
//覆蓋可以覆蓋所有所有字符
for(int i=1;i<=lenA;i++)
for(int j=1;j<=lenB;j++){
if(chA[i-1]==chB[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=0;
maxLen=Math.max(maxLen,dp[i][j]);
}
return maxLen;
}
}