Lintcode: Longest Common Substring 解题报告

时间:2023-03-09 01:41:00
Lintcode: Longest Common Substring  解题报告

Longest Common Substring

原题链接: http://lintcode.com/zh-cn/problem/longest-common-substring/#

Given two strings, find the longest common substring.

Return the length of it.

注意

The characters in substring should occur continiously in original string. This is different with subsequnce.

样例

标签 Expand

SOLUTION 1:

DP:
D[i][j] 定义为:两个string的前i个和前j个字符串,尾部连到最后的最长子串。
D[i][j] = 
1. i = 0 || j = 0 : 0
2. s1.char[i - 1] = s2.char[j - 1] ? D[i-1][j-1] + 1 : 0;
另外,创建一个max的缓存,不段更新即可。
 public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here
if (A == null || B == null) {
return 0;
} int lenA = A.length();
int lenB = B.length(); // bug 1: use error init.
int[][] D = new int[lenA + 1][lenB + 1]; int max = 0; // BUG 2: should use <= instead of <
for (int i = 0; i <= lenA; i++) {
for (int j = 0; j <= lenB; j++) {
if (i == 0 || j == 0) {
D[i][j] = 0;
} else {
if (A.charAt(i - 1) == B.charAt(j - 1)) {
D[i][j] = D[i - 1][j - 1] + 1;
} else {
D[i][j] = 0;
}
} max = Math.max(max, D[i][j]);
}
} return max;
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/dp/LongestCommonSubstring.java