首页 > 代码库 > Longest Common Substring
Longest Common Substring
Given two strings, find the longest common substring. Return the length of it. Notice The characters in substring should occur continuously in original string. This is different with subsequence. Have you met this question in a real interview? Yes Example Given A = "ABCD", B = "CBCE", return 2. Challenge O(n x m) time and memory.
区别于 Longest Common Subsequence 这是累加求subString 的
状态设为遍历到当前的i, j时的结果值, 但是却是不对, 是因为求得是累加的值,
Input
"www.lintcode.com code", "www.ninechapter.com code"
Output
17
Expected
9
for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); if (A.charAt(i - 1) == B.charAt(j - 1)) { f[i][j] = Math.max(f[i - 1][j - 1] + 1, f[i][j]); } } }
和这样写无差异, 都是求的累加和.
if (A.charAt(i - 1) == B.charAt(j - 1)) { f[i][j] = f[i - 1][j - 1] + 1; } else { f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); }
因此要改下状态(根据结果来设定状态需要那几个变量表示, 这个状态跟), : 匹配到的字符是最后一个字符的结果值(作为局部变量 ) + 全局变量
常见状态:
1遍历到当前字符时的最优解,
2 遍历到当前字符,字符如果是题意要求的string的局部解
方程: 分情况讨论, 根据题意与当前字符的形态和上个状态做转化
public int longestCommonSubstring(String A, String B) { // write your code here //state int n = A.length(); int m = B.length(); int[][] f = new int[n + 1][m + 1]; //initialize for (int i = 0; i <= n; i++) { f[i][0] = 0; } for (int i = 0; i <= m; i++) { f[0][i] = 0; } int ans = 0; //function for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (A.charAt(i - 1) == B.charAt(j - 1)) { f[i][j] = f[i - 1][j - 1] + 1; } else { f[i][j] = 0; } ans = Math.max(f[i][j], ans); } } return ans; }
Longest Common Substring
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。