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);

----

Bottom up solution can be:

1. Init first row and first col value to zero

2. Then loop thought the data, If row latter and col latter is not the same, then take which is larger Max {the previous row same col value data[row-1][col], same row but previous col data[row][col-1]}

3. If they are the same, take data[row-1][col-1] + 1.

Source, Code

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

  1. Dynamic Programming | Set 4 (Longest Common Subsequence)

    首先来看什么是最长公共子序列:给定两个序列,找到两个序列中均存在的最长公共子序列的长度.子序列需要以相关的顺序呈现,但不必连续.例如,"abc", "abg", ...

  2. Dynamic Programming | Set 3 (Longest Increasing Subsequence)

    在 Dynamic Programming | Set 1 (Overlapping Subproblems Property) 和 Dynamic Programming | Set 2 (Opti ...

  3. 动态规划求最长公共子序列(Longest Common Subsequence, LCS)

    1. 问题描述 子串应该比较好理解,至于什么是子序列,这里给出一个例子:有两个母串 cnblogs belong 比如序列bo, bg, lg在母串cnblogs与belong中都出现过并且出现顺序与 ...

  4. [Algorithms] Longest Common Subsequence

    The Longest Common Subsequence (LCS) problem is as follows: Given two sequences s and t, find the le ...

  5. 1143. Longest Common Subsequence

    link to problem Description: Given two strings text1 and text2, return the length of their longest c ...

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

    Longest Common Subsequence Accepted : Submit : Time Limit : MS Memory Limit : KB Longest Common Subs ...

  7. 最长公共字串算法, 文本比较算法, longest common subsequence(LCS) algorithm

    ''' merge two configure files, basic file is aFile insert the added content of bFile compare to aFil ...

  8. 【牛客网】Longest Common Subsequence

    [牛客网]Longest Common Subsequence 发现只有d数组最格路 于是我们把前三个数组中相同的数记成一个三维坐标,同一个数坐标不会超过8个 从前往后枚举d,每次最多只会更新不超过8 ...

  9. LintCode Longest Common Subsequence

    原题链接在这里:http://www.lintcode.com/en/problem/longest-common-subsequence/ 题目: Given two strings, find t ...

随机推荐

  1. VS debug 简记

    近两日使用VS2013 Professional版本调试一个c源文件,过程中发现有几个bug,不知是IDE的问题还是我设置有问题,记在这里 1.下面的程序段A和B,区别只是for是否加花括号(标准C规 ...

  2. spring in action 学习笔记三:对spring 容器的理解,以及如何利用AnnotationConfigApplicationContext这个容器创建对象

    一:spring的容器就是bean所居住的地点,这个居民点有很多的bean,有外来的bean(相当于创建了一个bean),有出去谋生的(相当于消亡了一个bean),他们之间都有某种联系 (bean与b ...

  3. Pandas之DataFrame——Part 3

    ''' [课程2.] 数值计算和统计基础 常用数学.统计方法 ''' # 基本参数:axis.skipna import numpy as np import pandas as pd df = pd ...

  4. SD卡给MCU升级

    目 录1. 前言2. 初识BootLoader2.1 百度百科的BootLoader2.2 BootLoader的简单理解2.3 BootLoader的作用3. BootLoader预备知识3.1 复 ...

  5. 汕头市队赛 SRM 08 B

    B-3 SRM 08 描述 给长度为 n 的数列 A 和长度为 m 的数列 B,问有多少长度为 m 的数列 C 满足 输入格式 第一行俩整数 n 和 m 第二行 n 个整数 ,表示数列 A 第三行 m ...

  6. rootkit 内核函数hook

    转自:https://0x90syntax.wordpress.com/2016/02/21/suterusu-rootkitx86%e4%b8%8earm%e7%9a%84%e5%86%85%e8% ...

  7. sed 使用总结

    1. 更新区间值 文件的内容如下: <ClientVersion> <Item> <ProductUuid>5fa7d5af-6f6a-4d1f-b773-ac42 ...

  8. MYSQL的longtext字段能放多少数据?

    生产上遇到问题, 同事说MYSQL里的字段放不下5m大小的数据. 于是,将django model里textfield里的max_length变长了. 依然无效, 于是,更改mysql的设置: set ...

  9. R 语言词云wordcloud

    来源:http://blog.chinaunix.net/uid-25135004-id-4311592.html wordcloud函数--用于绘制词云图 用法: wordcloud(words,f ...

  10. 由"软件是干什么的"引发的思考

            自工作以来,都只在进行模块的开发,很少站在整个项目的角度思考过.甚至,自己开发的软件,自己都没有去用过,包括开发的一些APP,都没有下载来认真体验过.思考过.却对自己手机上那些用过的A ...