给出两个字符串,找到最长公共子串,并返回其长度。
样例
给出A=“ABCD”,B=“CBCE”,返回 2
注意
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
思路:DP。
public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
int lenA=A.length();
int lenB=B.length();
if(lenA==0||lenB==0)
return 0;
int[][] buf=new int[lenA+1][lenB+1];
for(int i=0;i<=lenA;i++)
buf[i][0]=0;
for(int j=0;j<=lenB;j++)
buf[0][j]=0;
int sum=0;
for(int i=1;i<=lenA;i++)
for(int j=1;j<=lenB;j++)
{
if(A.charAt(i-1)==B.charAt(j-1))
{
buf[i][j]=buf[i-1][j-1]+1;
if(buf[i][j]>sum)
sum=buf[i][j];
}
else
buf[i][j]=0;
}
return sum;
}
}