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
  1. '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
  1. Max {
  2. LCS('DEB', 'EBC'),
  3. LCS('CDEB', 'BC')
  4. }

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').

  1. /**
  2. * FIND THE LONGEST COMMON SEQUENCES BY USING DYNAMICE PROGRAMMING
  3. *
  4. * @params:
  5. * str1: string
  6. * str2: string
  7. * i1: number
  8. * i2: number
  9. * memo: array []
  10. *
  11. * TC: O(L*M) << O(2^(L*M))
  12. */
  13.  
  14. function LCS(str1, str2) {
  15. const memo = [...Array(str1.length)].map(e => Array(str2.length));
  16.  
  17. /**
  18. * @return longest common sequence string
  19. */
  20. function helper(str1, str2, i1, i2, memo) {
  21. console.log(`str1, str2, ${i1}, ${i2}`);
  22. // if the input string is empty
  23. if (str1.length === i1 || str2.length === i2) {
  24. return "";
  25. }
  26. // check the memo, whether it contians the value
  27. if (memo[i1][i2] !== undefined) {
  28. return memo[i1][i2];
  29. }
  30. // if the first latter is the same
  31. // "A" + LCS(CDEB, EBC)
  32. if (str1[i1] === str2[i2]) {
  33. memo[i1][i2] = str1[i1] + helper(str1, str2, i1 + 1, i2 + 1, memo);
  34. return memo[i1][i2];
  35. }
  36.  
  37. // Max { "C" + LCS(DEB, EBC), "E" + LCB(CDEB, BC) }
  38. let result;
  39. const resultA = helper(str1, str2, i1 + 1, i2, memo); // L
  40. const resultB = helper(str1, str2, i1, i2 + 1, memo); // M
  41.  
  42. if (resultA.length > resultB.length) {
  43. result = resultA;
  44. } else {
  45. result = resultB;
  46. }
  47.  
  48. memo[i1][i2] = result;
  49. return result;
  50. }
  51.  
  52. return {
  53. result: helper(str1, str2, 0, 0, memo),
  54. memo
  55. };
  56. }
  57.  
  58. //const str1 = "I am current working in Finland @Nordea",
  59. //str2 = "I am currently working in Finland at Nordea";
  60.  
  61. const str1 = "ACDEB",
  62. str2 = "GAEBC";
  63.  
  64. const { result, memo } = LCS(str1, str2);
  65. console.log(
  66. `
  67. ${str1}
  68. ${str2}
  69. 's longest common sequence is
  70. "${result === "" ? "Empty!!!" : result}"
  71. `
  72. );
  73.  
  74. 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. vue(三)

    一.vue的特点 1.响应式的数据绑定(一旦修改了数据,立马更新视图) 数据驱动思想 (数据到视图的映射.操作数据改变视图.简化对DOM的操作) 追踪依赖变化 (  Object.defineProp ...

  2. js对象和jq对象互相转换

    1.DOM 对象转成 jQuery 对象 var v = document.getElementById("v"); //DOM对象 var $v = $(v); //jQuery ...

  3. [poj_3469]多核CPU

    Sample Input 3 1 1 10 2 10 10 3 2 3 1000 Sample Output 13 最小割,把模块看做点,建源点s和汇点t,以下(a,b,c)表示从a向b连一条容量为c ...

  4. IAT Hook

    @author: dlive 0X01 IAT Hook的优缺点 优点:工作原理与实现都比较简单 缺点:如果想钩取的API不在目标进程的IAT中,那么就无法使用该技术进行钩取操作.即如果要钩取的API ...

  5. Error C1189: #error: Please use the /MD switch for _AFXDLL builds(转)

    原文转自 https://www.cnblogs.com/zwh0214/p/6048360.html 在VS 2013中编译程序时出现错误: 错误提示1: error C1189: #error : ...

  6. RobotFramework自动化1-环境搭建【转载】

    本篇转自博客:上海-悠悠 原文地址:http://www.cnblogs.com/yoyoketang/tag/robotframework/ 前言 Robot Framework是一款python编 ...

  7. .net core 发布iis 错误

    点击iis功能,例如 点击log日志,提示xxx路径下的web.config错误 百度之后 安装NET Core Windows Server Hosting ->DotNetCore.2.0. ...

  8. Codeforces Round #447 (Div. 2) A. QAQ【三重暴力枚举】

    A. QAQ time limit per test 1 second memory limit per test 256 megabytes input standard input output ...

  9. Python的并发并行[4] -> 并发[1] -> concurrent.future 模块

    concurrent.future 模块 1 thread模块 / thread Module 1.1 常量 / Constants Pass 1.2 函数 / Function Pass 1.3 类 ...

  10. WSS3SDK之:服务器和站点架构:对象模型概览

    源出处:http://www.cnblogs.com/Sunmoonfire/archive/2011/01/18/1937884.html Windows SharePoint Services提供 ...