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. 如何把HTML标记分类

    p.h1.或div等元素常常称为块级元素,这些元素显示为一块内容:Strong,span等元素称为行内元素,它们的内容显示在行中,即“行内框”.(可以使用display=block将行内元素转换成块元 ...

  2. 【LeetCode-面试算法经典-Java实现】【101-Symmetric Tree(对称树)】

    [101-Symmetric Tree(对称树)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a binary tree, check whether ...

  3. 点滴积累【other】---存储过程删除所有表中的数据(sql)

    USE [QG_Mis24] GO /****** Object: StoredProcedure [dbo].[p_set1] Script Date: 07/18/2013 13:25:57 ** ...

  4. 点滴积累【JS】---JS小功能(setInterval实现图片效果显示时间)

    效果: 代码: <head runat="server"> <title></title> <script type="text ...

  5. Java自带命令详解

    1. 背景 给一个系统定位问题的时候,知识.经验是关键基础,数据(运行日志.异常堆栈.GC日志.线程快照[threaddump / javacore文件].堆转储快照[heapdump / hprof ...

  6. atitit.验证码识别step3----去除边框---- 图像处理类库 attilax总结java版本

    atitit.验证码识别step3----去除边框---- 图像处理类库 attilax总结java版本 1. 去除边框思路原理 1 2. Thumbnailator 是一个用来生成图像缩略图.裁切. ...

  7. [svc]salt-webui

    CherryPy https://pypi.python.org/packages/source/C/CherryPy/CherryPy-3.2.4.tar.gz#md5=e2c8455e15c39c ...

  8. Yii2基础常用笔记

    表单验证规则写在model类里,例如: 通过表单输入的值给模型属性填充数据用模型对象的load方法. $model->load(Yii::$app->request->post())

  9. 折腾gcc/g++链接时.o文件及库的顺序问题(转)

    转自: http://www.cnblogs.com/OCaml/archive/2012/06/18/2554086.html#sec-1-1 折腾gcc/g++链接时.o文件及库的顺序问题 Tab ...

  10. php socket 模型及效率问题

    // 创建套接字 socket_create(); // 绑定 socket_bind(); // 监听 socket_listen(); // 主体, 死循环 while(true){ // sel ...