[LintCode] Longest Common Subsequence

烈酒焚心 提交于 2020-01-10 15:39:11

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!