标签:
Given two strings, find the longest common substring.
Return the length of it.
Given A = "ABCD"
, B = "CBCE"
, return 2
.
The characters in substring should occur continuously in original string. This is different with subsequence.
O(n x m) time and memory.
SOLUTION:
DP经典题。
状态: 如果是这种比较经典的最大最小,总数,问题,直接结合问题去做状态。f(i, j) = A以(i)结尾,B以(j)结尾时,LCS
方程: 1,i,j位置字母相同 直接+1。 2不相同的话直接为零。
初始化:初始化为0.
答案,f(i,j)中的最大值。
public class Solution { /** * @param A, B: Two string. * @return: the length of the longest common substring. */ public int longestCommonSubstring(String A, String B) { int[][] result = new int[A.length() + 1][B.length() + 1]; if (A == null || B == null){ return 0; } 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)){ result[i][j] = result[i - 1][j - 1] + 1; } else { result[i][j] = 0; } max = Math.max(max, result[i][j]); } } return max; } }
[LintCode] Longest Common Substring
标签:
原文地址:http://www.cnblogs.com/tritritri/p/4955109.html