LintCode Longest Common Substring
2016-04-03 13:55
435 查看
原题链接在这里:http://www.lintcode.com/en/problem/longest-common-substring/#
题目:
Given two strings, find the longest common substring.
Return the length of it.
The characters in substring should occur continuously in original string. This is different with subsequence.
Example
Given A =
Challenge
O(n x m) time and memory.
题解:
与Longest Common Subsequence相似.
DP. 参考http://www.geeksforgeeks.org/longest-common-substring/
dp[i][j]表示长度为i的str1 和 长度为j的str2 longest common substring长度.
看两个substring 的 suffix.
dp[i][j] = dp[i-1][j-1] + 1 if str1.charAt(i-1) == str2.charAt(j-1).
dp[i][j] = 0. o.w
Time Complexity: O(m*n). Space: O(m*n).
AC Java:
题目:
Given two strings, find the longest common substring.
Return the length of it.
The characters in substring should occur continuously in original string. This is different with subsequence.
Example
Given A =
"ABCD", B =
"CBCE", return
2. "BC"
Challenge
O(n x m) time and memory.
题解:
与Longest Common Subsequence相似.
DP. 参考http://www.geeksforgeeks.org/longest-common-substring/
dp[i][j]表示长度为i的str1 和 长度为j的str2 longest common substring长度.
看两个substring 的 suffix.
dp[i][j] = dp[i-1][j-1] + 1 if str1.charAt(i-1) == str2.charAt(j-1).
dp[i][j] = 0. o.w
Time Complexity: O(m*n). Space: O(m*n).
AC Java:
public class Solution { /** * @param A, B: Two string. * @return: the length of the longest common substring. */ public int longestCommonSubstring(String A, String B) { if(A == null || B == null){ return 0; } int m = A.length(); int n = B.length(); int [][] dp = new int[m+1][n+1]; int longest = 0; for(int i = 1; i<=m; i++){ for(int j = 1; j<=n; j++){ if(A.charAt(i-1) == B.charAt(j-1)){ dp[i][j] = dp[i-1][j-1]+1; }else{ dp[i][j] = 0; } longest = Math.max(longest, dp[i][j]); } } return longest; } }
相关文章推荐
- psy & obv
- UVA - 1642 Magical GCD 数学
- java 文件读写,查找文件部署的位置
- MyEclipse 快捷键大全
- hdu1521 排列组合(指数型母函数)
- Qt 应用程序图标设置
- 例程7. HMC5883工程说明 -- 慕司板IAP15
- linux系统调用
- 2016.4.3 JS学习
- sublime的追加
- KNN的简单实现
- nasm汇编语言小程序:计算多个指定位置的Fibonacci值
- 时间类
- 依赖注入那些事儿
- 安卓中图片名称和id和drawable的互相关系
- hdu2082 找单词 (母函数)
- 水平listview
- 算法杂货铺——分类算法之决策树(Decision tree)
- Oracle中count()函数 注意点
- 3932: [CQOI2015]任务查询系统