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. 跨浏览器的CORS

    function createCORSRequest(method, url){ var xhr = new XMLHttpRequest(); if("withCredentials&qu ...

  2. 自制MVC框架基础插件介绍

    本文介绍的基础插件不是实现BeforehandCommonAttribute或ProceedPlugin的postsharp插件,这些都是自定义的基础性的拦截,而且在项目中经常用到. 1). Comp ...

  3. Android Studio 新手常见错误:Gradle DSL method not found: &#39;runProguard()&#39;

    在Android Studio上执行Github上的某Android开源项目,提示报错: Error:(20, 0) Gradle DSL method not found: 'runProguard ...

  4. iloc[[i]] 和 loc[[i]] 的区别

    In [2]: df Out[2]: A B 0 1.068932 -0.794307 2 -0.470056 1.192211 4 -0.284561 0.756029 6 1.037563 -0. ...

  5. Fiddler设置代理抓手机包

    启动Fiddler,打开菜单栏中的 Tools > Fiddler Options,打开“Fiddler Options”对话框. 在Fiddler Options”对话框切换到“Connect ...

  6. zookeeper(一):功能和原理

    简介 ZooKeeper 是一个开源的分布式协调服务,由雅虎创建,是 Google Chubby 的开源实现.分布式应用程序可以基于 ZooKeeper 实现诸如数据发布/订阅.负载均衡.命名服务.分 ...

  7. NGUI ScrollView中MoveRelative,Scroll的区别

    Scroll会计算边界,和直接拖拽的效果类似 MoveRelative不计算边界,超出边界了也不会管,也不会应用缓动效果

  8. 为什么 Objective-C 很难

    转自:http://www.oschina.net/question/213217_41058 作为一个Objective-C的coder,我总能听到一部分人在这门语言上抱怨有很多问题.他们总在想快速 ...

  9. c++11 on Android

    C++11 on Android The latest Andoird NDK r8e finally supports some of the most important C++11 librar ...

  10. makefile之调试信息

    makefile 调试 1. 添加调试信息 执行到error时会中断,warning不中断makefile的执行, info不打印当前makefile名和行号. a.$(warning "s ...