Longest Common Substring
来源:互联网 发布:大便出血 鲜红色 知乎 编辑:程序博客网 时间:2024/06/05 18:25
Given two strings, find the longest common substring.
Return the length of it.
Note
The characters in substring should occur continiously in original string. This is different with subsequnce.
Example
Given A=“ABCD”, B=“CBCE”, return 2
很著名的LCS问题。我们需要得到最大长度的公共子串的长度。如果暴力破解的话,首先得枚举出A所有的子串和B所有的子串,再根据比较得到最大长度的公共子串的长度,复杂度太高。
因此想到DP解法。
这里dp[i][j]可不是表示A的前i个字符与B的前j个字符的LCS。因为substring是连续的,对于这种连续的问题DP实际是记录当前元素“取或不取”。
所以dp[i][j]的含义是含有A中第i个字符和B中第j个字符的LCS。
dp[i][j] = dp[i - 1][j - 1] + 1 if A[i] == B[j]
dp[i][j] = 0 if A[i] != B[j]
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 int[][] dp = new int[A.length() + 1][B.length() + 1]; for(int i = 1; i < dp.length; i++){ for(int j = 1; j < dp[0].length; j++){ if(A.charAt(i - 1) == B.charAt(j - 1)){ dp[i][j] = dp[i - 1][j - 1] + 1; }else{ dp[i][j] = 0; } } } int max = 0; for(int i = 0; i < dp.length; i++){ for(int j = 0; j < dp[0].length; j++){ max = Math.max(max, dp[i][j]); } } return max; }}
0 0
- Longest common substring
- spoj1811 Longest Common Substring
- Longest Common Substring
- Longest common subsequence / substring
- HDU1403 Longest Common Substring
- Lintcode - Longest common substring
- longest common substring
- Longest Common Substring
- lintcode:Longest Common Substring
- [刷题]Longest Common Substring
- longest-common-substring
- Longest Common Substring
- PIQ19: Longest Common Substring
- Longest Common Substring
- #79 Longest Common Substring
- C - Longest Common Substring
- HDU1403-Longest Common Substring
- Longest Common Substring
- jquery插件jTemplates用法
- (1.3.3.1)插入排序:二路插入
- Android 开发中使用 SQLite 数据库的使用
- java类的生命周期_机制
- 商场如何通过无线认证提高人气
- Longest Common Substring
- CornerStone使用
- Spring @Resource、@Autowired、@Qualifier的注解注入及区别
- 读《海盗经济学》随笔一
- Bootstrap 教程
- ViewPager的PagerAdapter中的notifyDataSetChanged更新数据总结
- 如何把mysql数据导出成文本文件
- 如果是初学C语言请看完 一些成功人士的心得
- 二哥学算法之图(开篇)