lintcode-medium-Longest Common Subsequence
2016-03-26 03:08
429 查看
Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.
Example
For
For
动态规划:
用一个二维int数组表示A中前i个字符和B中前j个字符的LCS
状态转移:
当A的第i - 1个字符和B的第j - 1个字符相等时,dp[i][j] = dp[i - 1][j - 1] + 1
不相等时,选取dp[i - 1][j]和dp[i][j - 1]中较大的作为dp[i][j]的值
Your code should return the length of LCS.
Example
For
"ABCD"and
"EDCA", the LCS is
"A"(or
"D",
"C"), return
1.
For
"ABCD"and
"EACB", the LCS is
"AC", return
2.
动态规划:
用一个二维int数组表示A中前i个字符和B中前j个字符的LCS
状态转移:
当A的第i - 1个字符和B的第j - 1个字符相等时,dp[i][j] = dp[i - 1][j - 1] + 1
不相等时,选取dp[i - 1][j]和dp[i][j - 1]中较大的作为dp[i][j]的值
public class Solution { /** * @param A, B: Two strings. * @return: The length of longest common subsequence of A and B. */ public int longestCommonSubsequence(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] = dp[i - 1][j - 1] + 1; else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } return dp[m] ; } }
相关文章推荐
- FragmentTabHost切换Fragment时避免UI重新加载,Fragment保存状态
- 自定义GsonRequest
- UESTC 95 Ants Run! 水题
- iOS中关于UITableView下拉刷新控件UIRefreshController那点事
- 软件架构的条件(architecture prerequisite)
- emoji存入mysql报错 Incorrect string value: '\xF0\x90\x
- 关于iOS的due to uncaught exception 'CALayerInvalidGeometry'错误
- 大数据可视化工具Hue安装使用
- IOS开发UI篇—懒加载
- UI 开源代码 FileBrowserView
- execute、executeQuery和executeUpdate之间的区别
- 多线程:UIView 动画案例
- ERROR 1366 (HY000): Incorrect string value: '\xE5\xB8\x82' for column 'address' at row 1
- IOS 杂笔-11(实现在外部无法改变UIView的size)
- UE4 UriEncode 问题
- PHP include 和 require 语句
- soapui忘记准备,先上svn
- Sequence(优先队列,或堆)
- PriorityQueue
- UI图标使用规范