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 is a contiguous series of characters while subsequence is not necessarily. For example, "abc" is a both a substring and a subseqeunce of "abcde" while "ade" is only a subsequence.

This problem is a classic application of Dynamic Programming. Let's define the sub-problem (state) P[i][j] to be the length of the longest subsequence ends at i of s and j of t. Then the state equations are

  1. P[i][j] = max(P[i][j - 1], P[i - 1][j]) if s[i] != t[j];
  2. P[i][j] = P[i - 1][j - 1] + 1 if s[i] == t[j].

This algorithm gives the length of the longest common subsequence.  The code is as follows.

 int longestCommonSubsequence(string s, string t) {
int m = s.length(), n = t.length();
vector<vector<int> > dp(m + , vector<int> (n + , ));
for (int i = ; i <= m; i++)
for (int j = ; j <= n; j++)
dp[i][j] = (s[i - ] == t[j - ] ? dp[i - ][j - ] + : max(dp[i - ][j], dp[i][j - ]));
return dp[m][n];
}

Well, this code has both time and space complexity of O(m*n). Note that when we update dp[i][j], we only need dp[i - 1][j - 1], dp[i - 1][j] and dp[i][j - 1]. So we simply need to maintain two columns for them. The code is as follows.

 int longestCommonSubsequenceSpaceEfficient(string s, string t) {
int m = s.length(), n = t.length();
int maxlen = ;
vector<int> pre(m, );
vector<int> cur(m, );
pre[] = (s[] == t[]);
maxlen = max(maxlen, pre[]);
for (int i = ; i < m; i++) {
if (s[i] == t[] || pre[i - ] == ) pre[i] = ;
maxlen = max(maxlen, pre[i]);
}
for (int j = ; j < n; j++) {
if (s[] == t[j] || pre[] == ) cur[] = ;
maxlen = max(maxlen, cur[]);
for (int i = ; i < m; i++) {
if (s[i] == t[j]) cur[i] = pre[i - ] + ;
else cur[i] = max(cur[i - ], pre[i]);
maxlen = max(maxlen, cur[i]);
}
swap(pre, cur);
fill(cur.begin(), cur.end(), );
}
return maxlen;
}

Well, keeping two columns is just for retriving pre[i - 1], we can maintain a single variable for it and keep only one column. The code becomes more efficient and also shorter. However, you may need to run some examples to see how it achieves the things done by the two-column version.

 int longestCommonSubsequenceSpaceMoreEfficient(string s, string t) {
int m = s.length(), n = t.length();
vector<int> cur(m + , );
for (int j = ; j <= n; j++) {
int pre = ;
for (int i = ; i <= m; i++) {
int temp = cur[i];
cur[i] = (s[i - ] == t[j - ] ? pre + : max(cur[i], cur[i - ]));
pre = temp;
}
}
return cur[m];
}

Now you may try this problem on UVa Online Judge and get Accepted:)

Of course, the above code only returns the length of the longest common subsequence. If you want to print the lcs itself, you need to visit the 2-d table from bottom-right to top-left. The detailed algorithm is clearly explained here. The code is as follows.

 int longestCommonSubsequence(string s, string t) {
int m = s.length(), n = t.length();
vector<vector<int> > dp(m + , vector<int> (n + , ));
for (int i = ; i <= m; i++)
for (int j = ; j <= n; j++)
dp[i][j] = (s[i - ] == t[j - ] ? dp[i - ][j - ] + : max(dp[i - ][j], dp[i][j - ]));
int len = dp[m][n];
// Print out the longest common subsequence
string lcs(len, ' ');
for (int i = m, j = n, index = len - ; i > && j > ;) {
if (s[i - ] == t[j - ]) {
lcs[index--] = s[i - ];
i--;
j--;
}
else if (dp[i - ][j] > dp[i][j - ]) i--;
else j--;
}
printf("%s\n", lcs.c_str());
return len;
}

[Algorithms] Longest Common Subsequence的更多相关文章

  1. [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 subse ...

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

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

  3. LintCode Longest Common Subsequence

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

  4. [UCSD白板题] Longest Common Subsequence of Three Sequences

    Problem Introduction In this problem, your goal is to compute the length of a longest common subsequ ...

  5. LCS(Longest Common Subsequence 最长公共子序列)

    最长公共子序列 英文缩写为LCS(Longest Common Subsequence).其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已 ...

  6. Longest Common Subsequence

    Given two strings, find the longest common subsequence (LCS). Your code should return the length of  ...

  7. Longest Common Subsequence & Substring & prefix

    Given two strings, find the longest common subsequence (LCS). Your code should return the length of  ...

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

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

  9. Lintcode:Longest Common Subsequence 解题报告

    Longest Common Subsequence 原题链接:http://lintcode.com/zh-cn/problem/longest-common-subsequence/ Given ...

随机推荐

  1. 用 php 实现一个视图组件和模板引擎——基础

    只要不是做后端接口开发和一些作为守护进程之类的服务器脚本,大多数时候都是在和浏览器打交道,因此合理组织并展现 html 标签是最为常见的工作.一般大家使用框架时,都会自带有一套视图组件和模板引擎. 我 ...

  2. visual studio 2017发布dotnet core到docker

    docker的好处不用多说,有不了解的可移步<docker入门>,作为一个.net方面的老鸟也想早点搭上docker末班车,减少布署中的各种坑.以下我是在Visual Studio 201 ...

  3. socket 통신

    00.C# --> Application.ThreadException --> Application.Run --> Container --> Application. ...

  4. 两DD-WRT组建WDS设置

    今天把买了非常久的两台CISCO(已刷DD-WRT)路由器组成WDS,參考了三篇文章   DD-WRT v24-sp2的WDS中继设置 http://www.cnblogs.com/zjoch/arc ...

  5. [elk]elastalert邮箱告警

    本次要完成以下任务: 1.源码包安装elasticalert 2.配置邮箱报警 原则: 先很快的通过alert报警发一份邮件,其次了解alert配置文件各个选项 源码安装elasticalert 参考 ...

  6. jQuery 语法(一)

    通过 jQuery,您可以选取(查询,query) HTML 元素,并对它们执行“操作”(actions). jQuery 语法实例 $(this).hide() 演示 jQuery hide() 函 ...

  7. 动态加载图片的Adapter

    package com.example.cc.ecustapp.Adapter; import android.app.Activity;import android.content.Context; ...

  8. 1.3 Services - 服务

    服务是一种应用组件,它可以在后台执行耗时的操作,它是没有用户界面的.其它的应用组件都可以开启一个服务,服务开启后,即使用户离开了应用,服务仍然可以在后台运行.此外,绑定到服务的组件可以与服务进行交互, ...

  9. strspn&strcspn

    size_t strspn (const char *s,const char * accept); strspn返回s中第一个不在accept中出现过的字符下标. Returns an intege ...

  10. linux上FTP服务器搭建

    一.启动vsftpd服务 1. 启动VSFTP服务器 A. cenos下运行:yum install vsftpd B. 登录Linux主机后,运行命令:"service vsftpd st ...