码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Longest Common Subsequence

时间:2015-11-11 06:28:55      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Longest Common Subsequence

Given two strings, find the longest common subsequence (LCS).

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.

Clarification

What‘s the definition of Longest Common Subsequence?

 

SOLUTION :

先看问题,比较经典的dp问题,问length of LCS,两个string都要纪录,开一个二维数组纪录dp过程。

状态: f(x,y) A的前x跟B的前y个字母的最长LCS。

方程:既然是LCS,就要看A,B最后一位是否相同。

1,A(i) == B(j) == > f(i, j) = f (i - 1, j - 1) + 1

2, else ==> f (i,j) = f (i - 1, j) / f(i, j - 1) [就是要不然把A的最后一位扔掉,要不就把B的最后一位扔掉,看剩下的是否匹配]

初始化: 都是0就可以,所以不需要初始化,系统自动的

答案:f(A.len, B.len) 

技术分享
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) {
        int[][] result = new int[A.length() + 1][B.length() + 1];
        if (A == null || B == null){
            return 0;
        }
        
        //function
        //A[i] == B[j] ==> f(i, j) = f(i - 1, j - 1) + 1
        //A[i] != B[j] ==> f(i, j) = f(i - 1, j) / f(i, j - 1)
        for (int i = 1; i <= A.length(); i++){
            for (int j = 1; j <= B.length(); j++){
                if (A.charAt(i - 1) == B.charAt(j - 1)){
                    result[i][j] = result[i - 1][j - 1] + 1;
                } else {
                    result[i][j] = Math.max(result[i - 1][j], result[i][j - 1]);
                }
            }
        }
        return result[A.length()][B.length()];
    }
}
View Code

 

[LintCode] Longest Common Subsequence

标签:

原文地址:http://www.cnblogs.com/tritritri/p/4955102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!