最长公共子串
题目
给出两个字符串,找到最长公共子串,并返回其长度。
注意事项
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。样例
给出A=“ABCD”,B=“CBCE”,返回 2
题解
本题和77.Longest Common Subsequence-最长公共子序列(中等题)有很多相同之处,主要的区别在于最长公共序列可以不连续,而最长公共子串必须为连续字符。
同样采用动态规划的方法,状态转移方程为:
public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
int[][] lcs = new int[A.length()+1][B.length()+1];
int result = 0;
for (int i=1;i<=A.length();i++)
{
for (int j=1;j<=B.length();j++)
{
lcs[i][j] = (A.charAt(i-1) == B.charAt(j-1)) ? lcs[i-1][j-1] + 1 : 0;
result = Math.max(result,lcs[i][j]);
}
}
return result;
}
}
Last Update 2016.10.5