[LintCode] 最长公共子序列 Longest Common Subsequence

来源:互联网 发布:德国做律师 知乎 编辑:程序博客网 时间:2024/05/21 18:26

给出两个字符串,找到最长公共子序列(LCS),返回LCS的长度。

说明
最长公共子序列的定义:
最长公共子序列问题是在一组序列(通常2个)中找到最长公共子序列(注意:不同于子串,LCS不需要是连续的子串)。该问题是典型的计算机科学问题,是文件差异比较程序的基础,在生物信息学中也有所应用。
https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
样例
给出”ABCD” 和 “EDCA”,这个LCS是 “A” (或 D或C),返回1
给出 “ABCD” 和 “EACB”,这个LCS是”AC”返回 2

Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.

Clarification
What’s the definition of Longest Common Subsequence?
https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
http://baike.baidu.com/view/2020307.htm
Example
For “ABCD” and “EDCA”, the LCS is “A” (or “D”, “C”), return 1.
For “ABCD” and “EACB”, the LCS is “AC”, return 2.

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) {        if(null == A || null == B || A.length() == 0 || B.length() == 0) return 0;        int a_len = A.length(), b_len = B.length();        int [][] dp = new int[a_len+1][b_len+1];//strA[0,...,i-1]和strB[0,...,j-1]的最长公共子序列长度        for(int i = 1; i < a_len+1; i++) {            for(int j = 1; j < b_len+1; 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[a_len][b_len];    }}
0 0