---
title: "最大公共子字符串(Longest Common Substring)"
author: "backsnow"
date: "2011-09-26T17:15:09Z"
tags: []
categories: ["编程语言"]
slug: "longest-common-substring"
draft: false
lastmod: "2011-09-26T17:15:09Z"
id: 1180821
url: "https://backsnow.iteye.com/blog/1180821"
---

### [最大公共子字符串(Longest Common Substring)](http://kenby.iteye.com/blog/1012544)

- **博客分类：**
- [algorithms](http://kenby.iteye.com/category/176146)

Longest Common Substring和Longest Common Subsequence是有区别的

X = &lt;a, b, c, f, b, c&gt;

Y = &lt;a, b, f, c, a, b&gt;

X和Y的Longest Common Sequence为&lt;a, b, c, b&gt;，长度为4

X和Y的Longest Common Substring为 &lt;a, b&gt;长度为2

其实Substring问题是Subsequence问题的特殊情况，也是要找两个递增的下标序列

&lt;i1, i2, ...ik&gt; 和 &lt;j1, j2, ..., jk&gt;使

xi1 == yj1

xi2 == yj2

......

xik == yjk

与Subsequence问题不同的是，Substring问题不光要求下标序列是递增的，还要求每次

递增的增量为1， 即两个下标序列为：

&lt;i, i+1, i+2, ..., i+k-1&gt; 和 &lt;j, j+1, j+2, ..., j+k-1&gt; 

 

类比Subquence问题的动态规划解法，Substring也可以用动态规划解决，令

c\[i]\[j]表示以X\[i]和Y\[i]结尾的公共子串的长度，如果X\[i]不等于Y\[i]，则c\[i]\[j]等于0, 比如

X = &lt;y, e, d, f&gt;

Y = &lt;y, e, k, f&gt;

c\[1]\[1] = 1

c\[2]\[2] = 2

c\[3]\[3] = 0

c\[4]\[4] = 1

动态转移方程为：

如果xi == yj， 则 c\[i]\[j] = c\[i-1]\[j-1]+1

如果xi ! = yj,  那么c\[i]\[j] = 0

 

最后求Longest Common Substring的长度等于

max{c\[i]\[j], 1&lt;=i&lt;=n, 1&lt;=j&lt;=m}

 

C代码  [![收藏代码](http://kenby.iteye.com/images/icon_star.png)](http://kenby.iteye.com/blog/1012544 "收藏这段代码")

01. #include &lt;stdio.h&gt;
02. #include &lt;string.h&gt;
03. //#define DEBUG
04. #ifdef DEBUG
05. #define debug(...) printf( \_\_VA\_ARGS\_\_)
06. #else
07. #define debug(...)
08. #endif
09. #define N 250
10. int     c\[N]\[N];
11. void print\_str(char \*s1, char \*s2, int i, int j)
12. {
13. if (s1\[i] == s2\[j]) {
14. print\_str(s1, s2, i-1, j-1);
15. putchar(s1\[i]);
16. }
17. }
18. int common\_str(char \*s1, char \*s2)
19. {
20. int     i, j, n, m, max\_c;
21. int     x, y;
22. n = strlen(s1);
23. m = strlen(s2);
24. max\_c = -1;
25. for (i = 1; i &lt;= n; i++) {
26. for (j = 1; j &lt;= m; j++) {
27. if (s1\[i-1] == s2\[j-1]) {
28. c\[i]\[j] = c\[i-1]\[j-1] + 1;
29. }
30. else {
31. c\[i]\[j] = 0;
32. }
33. if (c\[i]\[j] &gt; max\_c) {
34. max\_c = c\[i]\[j];
35. x = i;
36. y = j;
37. }
38. debug("c\[%d]\[%d] = %d\\n", i, j, c\[i]\[j]);
39. }
40. }
41. print\_str(s1, s2, x-1, y-1);
42. printf("\\n");
43. return max\_c;
44. }
45. int main()
46. {
47. char    s1\[N], s2\[N];
48. while (scanf("%s%s", s1, s2) != EOF) {
49. debug("%s %s\\n", s1, s2);
50. printf("%d\\n", common\_str(s1, s2));
51. }
52. return 0;
53. }