最大公共子字符串(Longest Common Substring)

Longest Common Substring和Longest Common Subsequence是有區別的

X = <a, b, c, f, b, c>

Y = <a, b, f, c, a, b>

X和Y的Longest Common Sequence爲<a, b, c, b>,長度爲4

X和Y的Longest Common Substring爲 <a, b>長度爲2

其實Substring問題是Subsequence問題的特殊情況,也是要找兩個遞增的下標序列

<i1, i2, ...ik> 和 <j1, j2, ..., jk>使

xi1 == yj1

xi2 == yj2

......

xik == yjk

與Subsequence問題不同的是,Substring問題不光要求下標序列是遞增的,還要求每次

遞增的增量爲1, 即兩個下標序列爲:

<i, i+1, i+2, ..., i+k-1> 和 <j, j+1, j+2, ..., j+k-1> 

 

類比Subquence問題的動態規劃解法,Substring也可以用動態規劃解決,令

c[i][j]表示以X[i]和Y[i]結尾的公共子串的長度,如果X[i]不等於Y[i],則c[i][j]等於0, 比如

X = <y, e, d, f>

Y = <y, e, k, f>

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<=i<=n, 1<=j<=m}

 

C代碼  收藏代碼
  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. //#define DEBUG  
  5.   
  6. #ifdef DEBUG  
  7. #define debug(...) printf( __VA_ARGS__)   
  8. #else  
  9. #define debug(...)  
  10. #endif  
  11.   
  12. #define N 250  
  13.   
  14. int     c[N][N];  
  15.   
  16. void print_str(char *s1, char *s2, int i, int j)  
  17. {  
  18.     if (s1[i] == s2[j]) {  
  19.         print_str(s1, s2, i-1, j-1);  
  20.         putchar(s1[i]);  
  21.     }  
  22. }  
  23.   
  24. int common_str(char *s1, char *s2)  
  25. {  
  26.     int     i, j, n, m, max_c;  
  27.     int     x, y;  
  28.   
  29.     n = strlen(s1);  
  30.     m = strlen(s2);  
  31.   
  32.     max_c = -1;  
  33.     for (i = 1; i <= n; i++) {  
  34.         for (j = 1; j <= m; j++) {  
  35.             if (s1[i-1] == s2[j-1]) {  
  36.                 c[i][j] = c[i-1][j-1] + 1;  
  37.             }  
  38.             else {  
  39.                 c[i][j] = 0;  
  40.             }  
  41.             if (c[i][j] > max_c) {  
  42.                 max_c = c[i][j];  
  43.                 x = i;  
  44.                 y = j;  
  45.             }  
  46.             debug("c[%d][%d] = %d\n", i, j, c[i][j]);  
  47.         }  
  48.     }  
  49.   
  50.     print_str(s1, s2, x-1, y-1);  
  51.     printf("\n");  
  52.     return max_c;  
  53. }  
  54.   
  55. int main()  
  56. {  
  57.     char    s1[N], s2[N];  
  58.   
  59.     while (scanf("%s%s", s1, s2) != EOF) {  
  60.         debug("%s %s\n", s1, s2);  
  61.         printf("%d\n", common_str(s1, s2));  
  62.     }  
  63.     return 0;  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章