Lintcode: Longest Common Subsequence
2015-03-09 08:11
357 查看
Given two strings, find the longest comment subsequence (LCS). Your code should return the length of LCS. Example For "ABCD" and "EDCA", the LCS is "A" (or D or C), return 1 For "ABCD" and "EACB", the LCS is "AC", return 2
题目里说了:
Clarification
What's the definition of Longest Common Subsequence?
*(Note that a subsequence is different from a substring, for the terms of the former need not be consecutive terms of the original sequence.) It is a classic computer science problem, the basis of file comparison programs such as diff, and has applications in bioinformatics.
1. D[i][j] 定义为s1, s2的前i,j个字符串的最长common subsequence.
2. D[i][j] 当char i == char j, 可以有三种选择,D[i - 1][j - 1] + 1,D[i ][j - 1], D[i - 1][j] ,取最大的
当char i != char j, D[i ][j - 1], D[i - 1][j] 里取一个大的(因为最后一个不相同,所以有可能s1的最后一个字符会出现在s2的前部分里,反之亦然。
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 int[][] res = new int[A.length()+1][B.length()+1]; for (int i=1; i<=A.length(); i++) { for (int j=1; j<=B.length(); j++) { res[i][j] = Math.max(A.charAt(i-1)==B.charAt(j-1)? res[i-1][j-1]+1 : res[i-1][j-1], Math.max(res[i-1][j], res[i][j-1])); } } return res[A.length()][B.length()]; } }
相关文章推荐
- lintcode longest-common-subsequence 最长公共子序列 证明
- Lintcode - Longest common subsequence
- LintCode Longest Common Subsequence
- LintCode Longest Common Subsequence(最长公共子序列长度,动态规划入门题)
- LintCode Longest Common Substring
- lintcode :longest common substring 最长公共子串
- lintcode-medium-Longest Common Prefix
- lintcode: Longest Common Prefix
- LintCode Longest Increasing Continuous Subsequence
- lintcode:Longest Increasing Continuous subsequence II
- LintCode: Longest Increasing Continuous subsequence
- LintCode Longest Common Substring
- lintcode longest-increasing-continuous-subsequence 最长上升连续子序列
- LintCode-Longest Common Substring
- LintCode Longest Increasing Continuous subsequence II
- codewars—Longest Common Subsequence
- lintcode-easy-Longest Increasing Continuous Subsequence
- LintCode "Longest Increasing Subsequence"
- lintcode:Longest Common Substring
- LintCode "Longest Increasing Continuous subsequence II" !!