2. DP_最长公共子序列

一、题目

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

Your code should return the length of LCS.
Have you met this question in a real interview?
Yes

Example
For "ABCD" and "EDCA", the LCS is "A" (or "D", "C"), return 1.
For "ABCD" and "EACB", the LCS is "AC", return 2.

**Notice that the subsequence may be discontinuous in these original sequences.

二、解题思路

求『最长』类的题目往往与动态规划有点关系,这里是两个字符串,故应为双序列动态规划。比较基础的题。

以 f[i][j] 表示字符串 A 的前 i 位和字符串 B 的前 j 位的最长公共子序列数目。

  • 若 A[i] == B[j], 则分别去掉这两个字符后,原 LCS 数目减一。所以在 A[i] == B[j] 时 LCS 最多只能增加1。即:f[i][j] = f[i-1][j-1]+1。

  • 而在 A[i] != B[j] 时,由于A[i] 或者 B[j] 不可能同时出现在最终的 LCS 中,故这个问题可进一步缩小, f[i][j] = max(f[i - 1][j], f[i][j - 1]) .

三、解题代码

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 (A == null || A.length() == 0) return 0;  
        if (B == null || B.length() == 0) return 0;  
  
        int lenA = A.length();  
        int lenB = B.length();  
        int[][] lcs = new int[1 + lenA][1 + lenB];  
  
        for (int i = 1; i < 1 + lenA; i++) {  
            for (int j = 1; j < 1 + lenB; j++) {  
                if (A.charAt(i - 1) == B.charAt(j - 1)) {  
                    lcs[i][j] = 1 + lcs[i - 1][j - 1];  
                } else {  
                    lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]);  
                }  
            }  
        }  
  
        return lcs[lenA][lenB];  
    }  
}  

下一篇: 3. DP_Lintcode76 最长增长(上升)子序列Longest Increasing Subsequence solution
上一篇: 1. DP_LeetCode114. Distinct Subsequences

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 动态规划(Dynamic Programming) 本文包括: 动态规划定义 状态转移方程 动态规划算法步骤 最长...
    廖少少阅读 8,654评论 0 18
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,148评论 0 2
  • 2014暮夏到2015初秋这一年里 我好像经历了好多又好像什么也没有经历 这不是多事之秋 也没发生什么大事 这个...
    1d7de5c1f912阅读 1,183评论 0 1
  • Java GC优化速查表 her0kings1ey 本文是基于Java Performance The Defin...
    her0kings1ey阅读 3,529评论 1 3
  • 都说酒逢知己千杯少,也就是为了突出知己的难得,可以多喝几杯。打小就爱陪老爸举个杯,也就喝个陪伴,真的喝起来,也没什...
    玛莎Belle阅读 3,952评论 0 0