The Longest Common Substring (LCS) problem is as follows:

Given two strings s and t, find the length of the longest string r, which is a substring of both s and t.

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 substring ends at i of s and j of t. Then the state equations are

  1. P[i][j] = 0 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 substring. If we want the substring itself, we simply find the largest P[i][j] and return s.substr(i - P[i][j] + 1, P[i][j]) or t.substr(j - P[i][j] + 1, P[i][j]).

Then we have the following code.

 string longestCommonSubstring(string s, string t) {
int m = s.length(), n = t.length();
vector<vector<int> > dp(m, vector<int> (n, ));
int start = , len = ;
for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
if (i == || j == ) dp[i][j] = (s[i] == t[j]);
else dp[i][j] = (s[i] == t[j] ? dp[i - ][j - ] + : );
if (dp[i][j] > len) {
len = dp[i][j];
start = i - len + ;
}
}
}
return s.substr(start, len);
}

The above code costs O(m*n) time complexity and O(m*n) space complexity. In fact, it can be optimized to O(min(m, n)) space complexity. The observations is that each time we update dp[i][j], we only need dp[i - 1][j - 1], which is simply the value of the above grid before updates.

Now we will have the following code.

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

In fact, the code above is of O(m) space complexity. You may choose the small size for cur and repeat the same code using if..else.. to save more spaces :)

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

  1. SPOJ LCS2 - Longest Common Substring II

    LCS2 - Longest Common Substring II A string is finite sequence of characters over a non-empty finite ...

  2. LintCode Longest Common Substring

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

  3. Longest Common Substring

    Given two strings, find the longest common substring. Return the length of it. Example Given A = &qu ...

  4. 【SPOJ】1812. Longest Common Substring II(后缀自动机)

    http://www.spoj.com/problems/LCS2/ 发现了我原来对sam的理解的一个坑233 本题容易看出就是将所有匹配长度记录在状态上然后取min后再对所有状态取max. 但是不要 ...

  5. hdu 1403 Longest Common Substring(最长公共子字符串)(后缀数组)

    http://acm.hdu.edu.cn/showproblem.php?pid=1403 Longest Common Substring Time Limit: 8000/4000 MS (Ja ...

  6. 后缀自动机(SAM):SPOJ Longest Common Substring II

    Longest Common Substring II Time Limit: 2000ms Memory Limit: 262144KB A string is finite sequence of ...

  7. 后缀自动机(SAM) :SPOJ LCS - Longest Common Substring

    LCS - Longest Common Substring no tags  A string is finite sequence of characters over a non-empty f ...

  8. 后缀数组:HDU1043 Longest Common Substring

    Longest Common Substring Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java ...

  9. Longest Common Substring(最长公共子序列)

    Longest Common Substring Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Ot ...

随机推荐

  1. 贪吃蛇easyx版本

    这学期学了图形交互学,三个星期下来,突然意识到已经可以用c++写一个贪吃蛇了. 于是就用了两天写了这个小游戏. 其中一天写了核心代码,半天找核心代码中的bug,还有半天进行了界面及操作的优化. 但是有 ...

  2. Task WaitAll的用法

    var tasklst = new List<Task>(); ; i < urls.Count; i++) { tasklst.Add(Task.Factory.StartNew& ...

  3. 测试的一些基本概念知识(TCP )

    一.TCP报头部中的SYN.FIN.ACK: ACK : TCP协议规定,只有ACK=1时有效,也规定连接建立后所有发送的报文的ACK必须为1. SYN(SYNchronization) : 在连接建 ...

  4. convertView与ViewHolder有什么区别,好处在哪里

        convertView 在API中的解释是The old view to reuse, if possible, 第一次getView时还没有convertView,这时你便创建了一个新的vi ...

  5. FZU 2087 统计树边【MST相关】

     Problem 2087 统计树边 Accept: 212    Submit: 651 Time Limit: 1000 mSec    Memory Limit : 32768 KB  Prob ...

  6. Microsoft SQL Server Data Tools - Business Intelligence for Visual Studio 2013 SSIS

    VS2012 SSDTBI_VS2012_x86_CHS.exe http://www.microsoft.com/zh-CN/download/details.aspx?id=36843 VS201 ...

  7. 可能是最通俗易懂的 Java 位操作运算讲解

    https://blog.csdn.net/briblue/article/details/70296326

  8. 点滴积累【JS】---JS小功能(JS实现排序)

    效果: 思路: 首先,获得用到的ID,在把得到的<li>数组添加到array数组里面,然后在进行array排序,排序完后再将array中的数据用appendChild添加到ul里面: 代码 ...

  9. Mac Yosemite上安装macvim和YouCompleteMe

    今天在macvim上安装YouCompleteMe的时候,碰到一个运行vim崩溃的错误.查了半天终于解决! 先上一下安装macvim的过程 # install xcode and command li ...

  10. LFCS 系列第八讲:管理用户和用户组、文件权限和属性以及启用账户 sudo 访问权限

    由于 Linux 是一个多用户的操作系统(允许多个用户通过不同主机或者终端访问一个独立系统),因此你需要知道如何才能有效地管理用户:如何添加.编辑.禁用和删除用户账户,并赋予他们足以完成自身任务的必要 ...