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

给定两个字符串,目标是找到它们的最长公共子序列(LCS),并返回其长度。LCS不一定是连续子串,它在文件差异比较和生物信息学中有应用。例如,'ABCD'和'EDCA'的LCS为'A',返回1;'ABCD'和'EACB'的LCS为'AC',返回2。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给出两个字符串,找到最长公共子序列(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];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值