Longest Common Subsequence

Posted flagyuri

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Common Subsequence相关的知识,希望对你有一定的参考价值。

Description

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

Your code should return the length of LCS.

Clarification

Example

Example 1:
	Input:  "ABCD" and "EDCA"
	Output:  1
	
	Explanation:
	LCS is ‘A‘ or  ‘D‘ or ‘C‘


Example 2:
	Input: "ABCD" and "EACB"
	Output:  2
	
	Explanation: 
	LCS is "AC"
思路:Dp[i][j] 表示A序列前i个数,与B的前j个数的LCS长度。
对A的每个位置i,枚举B的每个位置j。
public class Solution {
    /**
     * @param A: A string
     * @param B: A string
     * @return: The length of longest common subsequence of A and B
     */
    public int longestCommonSubsequence(String A, String B) {
        int n = A.length();
        int m = B.length();
        int f[][] = new int[n + 1][m + 1];
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= m; j++){
                f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
                if(A.charAt(i - 1) == B.charAt(j - 1))
                    f[i][j] = f[i - 1][j - 1] + 1;
            }
        }
        return f[n][m];
    }
}

  



以上是关于Longest Common Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

1143. Longest Common Subsequence

1143. Longest Common Subsequence

leetcode14. longest common prefix

LintCode Longest Common Subsequence

LintCode Longest Common Substring

#Leetcode# 14. Longest Common Prefix