[Algorithms] Using Dynamic Programming to Solve longest common subsequence problem

Let‘s say we have two strings:

str1 = ‘ACDEB‘

str2 = ‘AEBC‘

We need to find the longest common subsequence, which in this case should be ‘AEB‘.

Using dynamic programming, we want to compare by char not by whole words.

  • we need memo to keep tracking the result which have already been calculated

    •   memo is 2d array, in this case is 5 * 4 array.
  • It devided problem into two parts
    •   If the char at the given indexs for both strings are the same, for example, ‘A‘ for str1 & str2, then we consider
‘A‘ + LSC(str1, str2, i1 + 1, i2 + 1)
    • If the char at the given indexs are not the same, we pick max length between LCB(‘DEB‘, ‘EBC‘) & LCB(‘CDEB‘, ‘BC‘),  we pick
Max {
   LCS(‘DEB‘, ‘EBC‘),
   LCS(‘CDEB‘, ‘BC‘)
}

Bacislly for the str1 = ‘CDEB‘ str2 = ‘EBC‘, the first char is not the same, one is ‘C‘, another is ‘E‘, then we devide into tow cases and get the longer one. The way to devide is cutting ‘C‘ from str1 get LCS(‘DEB‘, ‘EBC‘), and cutting ‘E‘ from str2 get LCS(‘CDEB‘, ‘BC‘).

 /**
 * FIND THE LONGEST COMMON SEQUENCES BY USING DYNAMICE PROGRAMMING
 *
 * @params:
 * str1: string
 * str2: string
 * i1: number
 * i2: number
 * memo: array []
 *
 * TC: O(L*M) << O(2^(L*M))
 */

function LCS(str1, str2) {
    const memo = [...Array(str1.length)].map(e => Array(str2.length));

    /**
     * @return longest common sequence string
     */
    function helper(str1, str2, i1, i2, memo) {
      console.log(`str1, str2, ${i1}, ${i2}`);
      // if the input string is empty
      if (str1.length === i1 || str2.length === i2) {
        return "";
      }
      // check the memo, whether it contians the value
      if (memo[i1][i2] !== undefined) {
        return memo[i1][i2];
      }
      // if the first latter is the same
      // "A" + LCS(CDEB, EBC)
      if (str1[i1] === str2[i2]) {
        memo[i1][i2] = str1[i1] + helper(str1, str2, i1 + 1, i2 + 1, memo);
        return memo[i1][i2];
      }

      // Max { "C" + LCS(DEB, EBC), "E" + LCB(CDEB, BC) }
      let result;
      const resultA = helper(str1, str2, i1 + 1, i2, memo); // L
      const resultB = helper(str1, str2, i1, i2 + 1, memo); // M

      if (resultA.length > resultB.length) {
        result = resultA;
      } else {
        result = resultB;
      }

      memo[i1][i2] = result;
      return result;
    }

    return {
      result: helper(str1, str2, 0, 0, memo),
      memo
    };
  }

  //const str1 = "I am current working in Finland @Nordea",
  //str2 = "I am currently working in Finland at Nordea";

  const str1 = "ACDEB",
    str2 = "GAEBC";

  const { result, memo } = LCS(str1, str2);
  console.log(
    `
     ${str1}
     ${str2}
     ‘s longest common sequence is
     "${result === "" ? "Empty!!!" : result}"
    `
  );

  console.log(memo);
  

Source, Code

原文地址:https://www.cnblogs.com/Answer1215/p/10206497.html

时间: 2024-11-14 00:03:08

[Algorithms] Using Dynamic Programming to Solve longest common subsequence problem的相关文章

Dynamic Programming | Set 4 (Longest Common Subsequence)

首先来看什么是最长公共子序列:给定两个序列,找到两个序列中均存在的最长公共子序列的长度.子序列需要以相关的顺序呈现,但不必连续.例如,"abc", "abg", "bdf", "aeg", '"acefg"等都是"abcdefg"的子序列.因此,一个长度为n的序列拥有2^n中可能的子序列(序列中的每一个元素只有选或者不选两种可能,因此是2^n). Example: LCS for inp

Longest Common Subsequence Problem

The longest common subsequence (LCS) problem is the problem of finding the longest subsequence common to all sequences in a set of sequences (often just two sequences). It differs from problems of finding common substrings: unlike substrings, subsequ

Dynamic Programming | Set 3 (Longest Increasing Subsequence)

在 Dynamic Programming | Set 1 (Overlapping Subproblems Property) 和 Dynamic Programming | Set 2 (Optimal Substructure Property) 中我们已经讨论了重叠子问题和最优子结构性质,现在我们来看一个可以使用动态规划来解决的问题:最长上升子序列(Longest Increasing Subsequence(LIS)). 最长上升子序列问题,致力于在一个给定的序列中找到一个最长的子序列

DP(dynamic programming)之LIS(longest increasing subsequence)问题(转)

今天回顾WOJ1398,发现了这个当时没有理解透彻的算法.看了好久好久,现在终于想明白了.试着把它写下来,让自己更明白. 最长递增子序列,Longest Increasing Subsequence 下面我们简记为 LIS.排序+LCS算法 以及 DP算法就忽略了,这两个太容易理解了. 假设存在一个序列d[1..9] = 2 1 5 3 6 4 8 9 7,可以看出来它的LIS长度为5.下面一步一步试着找出它.我们定义一个序列B,然后令 i = 1 to 9 逐个考察这个序列.此外,我们用一个变

[Algorithms] Longest Common Subsequence

The Longest Common Subsequence (LCS) problem is as follows: Given two sequences s and t, find the length of the longest sequence r, which is a subsequence of both s and t. Do you know the difference between substring and subequence? Well, substring i

1143. Longest Common Subsequence

link to problem Description: Given two strings text1 and text2, return the length of their longest common subsequence. A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without chan

2017-5-14 湘潭市赛 Longest Common Subsequence 想法题

Longest Common Subsequence Accepted : 7 Submit : 66 Time Limit : 3000 MS Memory Limit : 65536 KB Longest Common Subsequence Bobo has a sequence A=(a1,a2,-,an) of length n. He would like to know f(0),f(1),f(2) and f(3) where f(k) denotes the number of

AOJ_ALDS1_10_C Longest Common Subsequence【LCS+DP】

Longest Common Subsequence Aizu - ALDS1_10_C For given two sequences X and Y, a sequence Z is a common subsequence of X and Y if Z is a subsequence of both X and Y. For example, if X={a,b,c,b,d,a,b} and Y={b,d,c,a,b,a}, the sequence {b,c,a} is a comm

Longest Common Subsequence

Problem statement: 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 Clarification What's the definition of Longest Common Subsequence? https:/