lintcode-medium-Longest Common Substring
2016-03-26 06:43
302 查看
Given two strings, find the longest common substring.
Return the length of it.
Example
Given A =
Challenge
O(n x m) time and memory.
这道题和longest common subsequence差不多,也是动态规划,状态转移稍有区别:
一个二维int数组记录A前i个字符和B前j个字符的longest common subsequence
当A的第i - 1个字符和B的第j - 1个字符不相等时,dp[i][j]为之前的情况中数值最大的,即dp[i][j - 1]和dp[i - 1][j]中较大的
当两个字符相等时,必须从后往前数包括这两个字符的substring的长度是否大于dp[i][j - 1]和dp[i - 1][j],大于的话更新一下dp[i][j],否则和不相等时一样
Return the length of it.
Example
Given A =
"ABCD", B =
"CBCE", return
2.
Challenge
O(n x m) time and memory.
这道题和longest common subsequence差不多,也是动态规划,状态转移稍有区别:
一个二维int数组记录A前i个字符和B前j个字符的longest common subsequence
当A的第i - 1个字符和B的第j - 1个字符不相等时,dp[i][j]为之前的情况中数值最大的,即dp[i][j - 1]和dp[i - 1][j]中较大的
当两个字符相等时,必须从后往前数包括这两个字符的substring的长度是否大于dp[i][j - 1]和dp[i - 1][j],大于的话更新一下dp[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) { // write your code here if(A == null || A.length() == 0 || B == null || B.length() == 0) return 0; int m = A.length(); int n = B.length(); int[][] dp = new int[m + 1][n + 1]; dp[0][0] = 0; for(int i = 1; i <= m; i++) dp[i][0] = 0; for(int i = 1; i <= n; i++) dp[0][i] = 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] = Math.max(dp[i - 1][j], dp[i][j - 1]); } else{ int len = 0; while(i - len - 1 >= 0 && j - 1 - len >= 0 && A.charAt(i - 1 - len) == B.charAt(j - 1 - len)) len++; dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); dp[i][j] = Math.max(dp[i][j], len); } } } return dp[m] ; } }
相关文章推荐
- You need to use a Theme.AppCompat theme (or descendant) with this activity解决方法
- codevs 1269 匈牙利游戏 SPFA+次短路
- Android中PopupWindow的基本使用
- Access Violation at address 00000000.Read of address 00000000 解决办法
- Pi3 中文环境以及输入法
- 无屏无外设操作,SSH,VNC
- LeetCode Read N Characters Given Read4 II - Call multiple times
- 2016年寒假整理
- 如何每日增量加载数据到Hive分区表
- LeetCode Read N Characters Given Read4
- Python入门 之 迭代
- tx股票接口小计
- 2016年Web前端面试题目汇总
- C++ 值传递、指针传递、引用传递详解
- 构造函数
- ubuntu上怎么设置默认python命令是执行python3而不是python2
- android多线程
- 二叉树系列6:非递归遍历
- jsp+tomcat+ 创建工程 配置工程
- Asp.net MVC5 路由Html后缀的问题