求两字符串最长公共子序列——动态规划

   1.“两字符串最长公共子序列”的概念;

        一个字符串的子序列,是指从该字符串中去掉任意多个字符后剩下的字符在不改变顺序的情况下组成的新字符串。这个子序列是可以不连续的。最长公共子序列,是指多个字符串可具有的长度最大的公共的子序列。举个例子,如:有两条随机序列,如 1 3 4 5 5 and 2 4 5 5 7 6,则它们的最长公共子序列便是:4 5 5。

        注意最长公共子串和最长公共子序列的区别:

        最长公共子串(Longest Common Substirng)和最长公共子序列(Longest Common Subsequence,LCS)的区别为:子串是串的一个连续的部分,子序列则是从不改变序列的顺序,而从序列中去掉任意的元素而获得新的序列;也就是说,子串中字符的位置必须是连续的,子序列则可以不必连续。

         2.解决思路

    (1)穷举法    

        解最长公共子序列问题时最容易想到的算法是穷举搜索法,即对X的每一个子序列,检查它是否也是Y的子序列,从而确定它是否为X和Y的公共子序列,并且在检查过程中选出最长的公共子序列。X和Y的所有子序列都检查过后即可求出X和Y的最长公共子序列。X的一个子序列相应于下标序列{1, 2, …, m}的一个子序列,因此,X共有2m个不同子序列(Y亦如此,如为2^n),从而穷举搜索法需要指数时间(2^m * 2^n)。

    (2)动态规划算法

        最长公共子序列问题也有最优子结构性质。记:

        Xi=<x1,⋯,xi>,即X序列的前i个字符 (1≤i≤m)(前缀)
        Yj=<y1,⋯,yj>,即Y序列的前j个字符 (1≤j≤n)(前缀)
       假定Z=<z1,⋯,zk> ∈ LCS(X,Y),那么不难有以下结论:
        (1).若xm=yn(最后一个字符相同),则不难用反证法证明:该字符必是X与Y的任一最长公共子序列Z(设长度为k)的最后一个字符,即有zk = xm = yn 且显然有Zk-1∈LCS(Xm-1 , Yn-1)即Z的前缀Zk-1是Xm-1与Yn-1的最长公共子序列。此时,问题化归成求Xm-1与Yn-1的LCS(LCS(X , Y)的长度等于LCS(Xm-1 , Yn-1)的长度加1)。
        (2)若xm≠yn,则亦不难用反证法证明:要么Z∈LCS(Xm-1, Y),要么Z∈LCS(X , Yn-1)。由于zk≠xm与zk≠yn其中至少有一个必成立,若zk≠xm则有Z∈LCS(Xm-1 , Y),类似的,若zk≠yn 则有Z∈LCS(X , Yn-1)。此时,问题化归成求Xm-1与Y的LCS及X与Yn-1的LCS。LCS(X , Y)的长度为:max{LCS(Xm-1 , Y)的长度, LCS(X , Yn-1)的长度}。
        从上面的分析可以看出,解决这个层次的LCS问题,要求三个方面的东西:
        A:LCS(Xm-1,Yn-1)+1;
        B:LCS(Xm-1,Y),LCS(X,Yn-1);

        C:max{LCS(Xm-1,Y),LCS(X,Yn-1)}。

   3.算法实现

    (1)穷举法递归实现

        穷举法是比较如意想到的方法,但是时间复杂度太高,需要比较的字符串稍微大一点就不行了。并且,这种方法只能计算最长公共子序列的长度,无法计算具体的序列。

算法实现如下:

[cpp]  view plain  copy
  1. //1.穷举法:递归实现  
  2. int LCS(string x, string y, char* result, int xlen, int ylen, int relen, int i, int j){  
  3.     if(i < xlen && j < ylen){  
  4.         if(x[i] == y[j]){  
  5.             result[relen] = x[i];  
  6.             relen++;              
  7.             return 1 + LCS(x, y, result, xlen, ylen, relen, i+1, j+1);  
  8.         }else{  
  9.             int count_1 = LCS(x, y, result, xlen, ylen, relen, i, j + 1);  
  10.             int count_2 = LCS(x, y, result, xlen, ylen, relen, i + 1, j);  
  11.             return count_1 > count_2 ? count_1 : count_2;  
  12.         }  
  13.     }else{    
  14.         return 0;  
  15.     }  
  16. }  

     (2)动态规划算法递归实现(记忆化搜索)

      相对于穷举法来说,在时间效率上要好很多。为O(m*n)级别,但是由于涉及到多层次的递归调用,一定程度上影响了效率,但基本还可接受。该过程需要用到两个辅助数组,大小为tmp_1[m][n],tmp_2[m][n]。其中一个用来记录最长的子序列长度,另一个记录两个字符串相同字符的信息,据此回溯,就可以得到公共的子序列。

    (3)动态规划算法非递归实现(递推)

      仍然需要用到两个辅助数组,作用同(2)中一致,不过针对第一个数组(tmp_1)可以做一个优化,因为程序对其中每一个元素的计算只和它左边、上边、左上这三个元素相关,因此只需要保留这几个元素就可以了。因为程序是一行一行计算的,因此只保留两行内容就可以了,根据上面一行计算下面一行,两行交替使用。最终程序结束时的当前行最右侧的元素就是最大的子序列长度。


         4.时间复杂度分析

       (1)穷举法的时间复杂度:假设字符串X、Y长度分别为m、n,在字符串X的子序列中,任何一个字符都有可能出现,也可能不出现,因此,字符串X的子序列的所有可能组合为2^m种。同理字符串Y的所有子序列的可能组合有2^n种。要取得X、Y的所有公共子序列,需要进行2^m*2^n次比较,时间复杂度为 O(2^m*2^n),然后在从中选出一个或者多个最大的子序列,复杂度为O(2^m + 2^n)。总体复杂度为2^m*2^n。
       (2)动态规划法的时间复杂度:动态规划分两个过程,分别是构造公共子序列长度数组和构造最长公共子序列。构造公共子序列数组,数组中共有(m+1)* (n+1)个元素,计算他们的值时间复杂度为O(m*n);构造最长公共子序列过程复杂度为O(max(m,n))总体复杂度为O(m*n)。递归实现和非递归实现都是如此。

       (3)下面是针对实际例子的测试情况,字符串都是由程序随机产生:

字符串X长度

字符串Y长度

公共子序列长度

递归时间(ms

非递归时间(ms

20

30

7

10

0

200

300

75

82

2

500

1000

220

1302

17

2000

1000

441

11856

68

2000

3000

787

64898

191

       (4)从实际效果来看,动态规划算法的非递归实现要比递归实现效率高很多。可能是因为递归法需要创建函数、分配栈空间等开销较大所致。非递归的时间复杂度相对稳定,递归的发挥不是很稳定。

        5.完整源代码

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <string.h>  
  4. #include <time.h>  
  5. #include <sys/time.h>  
  6. #include <stdlib.h>  
  7. using namespace std;  
  8.   
  9.   
  10. const int X = 20, Y = 30;  
  11.   
  12. //1.穷举法:递归实现  
  13. int LCS(string x, string y, char* result, int xlen, int ylen, int relen, int i, int j){  
  14.     if(i < xlen && j < ylen){  
  15.         if(x[i] == y[j]){  
  16.             result[relen] = x[i];  
  17.             relen++;              
  18.             return 1 + LCS(x, y, result, xlen, ylen, relen, i+1, j+1);  
  19.         }else{  
  20.             int count_1 = LCS(x, y, result, xlen, ylen, relen, i, j + 1);  
  21.             int count_2 = LCS(x, y, result, xlen, ylen, relen, i + 1, j);  
  22.             return count_1 > count_2 ? count_1 : count_2;  
  23.         }  
  24.     }else{    
  25.         return 0;  
  26.     }  
  27. }  
  28.   
  29. int LCS_2(string x, string y, char* result, int xlen, int ylen, int relen, int i, int j){  
  30.     if(i >= 0 && j >= 0 && i < xlen && j < ylen){  
  31.         if(x[i] == y[j]){  
  32.             result[relen] = x[i];  
  33.             relen++;  
  34.             return 1 + LCS_2(x, y, result, xlen, ylen, relen, i - 1, j - 1);  
  35.         }else{  
  36.             int count_1 = LCS_2(x, y, result, xlen, ylen, relen, i, j - 1);  
  37.             int count_2 = LCS_2(x, y, result, xlen, ylen, relen, i - 1, j);  
  38.             return count_1 > count_2 ? count_1 : count_2;  
  39.               
  40.         }  
  41.     }  
  42.     return 0;  
  43. }  
  44.   
  45. //2.动态规划算法:递归实现(记忆化搜索)  
  46. int LCS_length_1(string x, string y, int tmp_1[][Y+1], int tmp_2[][Y+1], int xlen, int ylen, int i, int j){  
  47.     if(i >= 0 && j >= 0 && i <= xlen && j <= ylen){  
  48.         if(i == 0 || j == 0 || tmp_1[i][j] > 0){  
  49.             return tmp_1[i][j];  
  50.         }else{  
  51.             if(x[i-1] == y[j-1]){  
  52.                 tmp_2[i][j] = 0;  
  53.                 return tmp_1[i][j] = 1 + LCS_length_1(x, y, tmp_1, tmp_2, xlen, ylen, i-1, j-1);  
  54.             }else if((tmp_1[i][j-1] = LCS_length_1(x, y, tmp_1, tmp_2, xlen, ylen, i, j-1)) >=   
  55.                     (tmp_1[i-1][j] = LCS_length_1(x, y, tmp_1, tmp_2, xlen, ylen, i-1, j))){  
  56.                 tmp_2[i][j] = 1;  
  57.                 return tmp_1[i][j] = tmp_1[i][j-1];  
  58.             }else{  
  59.                 tmp_2[i][j] = -1;  
  60.                 return tmp_1[i][j] = tmp_1[i-1][j];  
  61.             }  
  62.         }  
  63.     }  
  64.       
  65.     return 0;     
  66. }  
  67.   
  68. //3.动态规划算法:非递归实现(递推实现,空间优化)  
  69. int LCS_length_2(string x, string y, int tmp_1[][Y+1], int tmp_2[][Y+1], int xlen, int ylen){  
  70.     int i = 0, j = 0, k = 0;  
  71.     //辅助数组的首行元素置为0  
  72.     for(i = 0; i <= xlen; i++){  
  73.         tmp_1[0][i] = 0;  
  74.     }  
  75.     tmp_1[1][0] = 0;  
  76.     //对数组内容进行写入  
  77.     for(i = 1; i <= xlen; i++){  
  78.         k = i%2;  
  79.         tmp_1[i%2][0] = 0;  
  80.         for(j = 1; j <= ylen; j++){  
  81.             if(x[i-1] == y[j-1]){  
  82.                 tmp_1[k][j] = tmp_1[(i-1)%2][j-1] + 1;  
  83.                 tmp_2[i][j] = 0;        //斜向下  
  84.             }else{  
  85.                 if(tmp_1[k][j-1] >= tmp_1[(i-1)%2][j]){  
  86.                     tmp_1[k][j] = tmp_1[k][j-1];  
  87.                     tmp_2[i][j] = 1;        //向右  
  88.                 }else{  
  89.                     tmp_1[k][j] = tmp_1[(i-1)%2][j];  
  90.                     tmp_2[i][j] = -1;       //向下  
  91.                 }  
  92.             }             
  93.         }  
  94.     }  
  95.     return tmp_1[(i-1)%2][j-1];  
  96. }  
  97.   
  98.   
  99. //最大公共子序列输出函数,非递归实现  
  100. int LCS_print_1(string x, char *result, int tmp_2[][Y+1], int xlen, int ylen){  
  101.     int i = xlen, j = ylen, k = 0;  
  102.     while(i > 0 && j > 0 ){  
  103.         if(tmp_2[i][j] == 0){  
  104.             result[k] = x[i-1];         //斜向下  
  105.             k++;  
  106.             i--;  
  107.             j--;  
  108.         }else if(tmp_2[i][j] == 1){  
  109.             j--;                    //向右  
  110.         }else if(tmp_2[i][j] == -1){  
  111.             i--;                    //向下  
  112.         }  
  113.     }  
  114.     return k;  
  115. }  
  116.   
  117. //-------------------------以下为测试代码----------------------------------------------------  
  118.   
  119. //1.测试穷举法递归实现  
  120. void test_1(string x, string y){  
  121.     char result[X];  
  122.     int xlen = x.length();  
  123.     int ylen = y.length();  
  124.     //int max_len = LCS(x, y, result, xlen, ylen, 0, 0, 0);  
  125.     int max_len = LCS_2(x, y, result, xlen, ylen, 0, xlen - 1, ylen - 1);  
  126.     cout << "1.穷举法递归求最长公共子序列:" << endl;  
  127.     cout << "  最大公共子序列长度为:" << max_len << endl;  
  128.     /* 
  129.     for(int i = 0; i < max_len; i++){ 
  130.         cout << result[i]; 
  131.     } 
  132.     cout << endl; 
  133.     */  
  134. }  
  135.   
  136. //2.测试动态规划算法递归实现  
  137. void test_2(string x, string y){  
  138.     //2.1参数处理  
  139.     char result[X+1];  
  140.     int xlen = x.length();  
  141.     int ylen = y.length();  
  142.     int tmp_1[X+1][Y+1] = {1};  
  143.     int tmp_2[X+1][Y+1] = {-2};  
  144.     //2.2初始化辅助数组  
  145.     memset(tmp_1,-1,sizeof(tmp_1));  
  146.     for(int i = 0; i <= xlen; i++){  
  147.         tmp_1[i][0] = 0;  
  148.     }  
  149.     for(int j = 0; j <= ylen; j++){  
  150.         tmp_1[0][j] = 0;  
  151.     }  
  152.     //2.3执行计算  
  153.     int max_len = LCS_length_1(x, y, tmp_1, tmp_2, xlen, ylen, xlen, ylen);  
  154.     LCS_print_1(x, result, tmp_2, xlen, ylen);    
  155.     //3.3打印结果  
  156.     cout << "2.动态规划法递归求最长公共子序列:" << endl;  
  157.     cout << "  最大公共子序列长度为:" << max_len << " 序列为:";  
  158.     for(int j = max_len - 1; j >= 0; j--){  
  159.         cout << result[j];  
  160.     }  
  161.     cout << endl;  
  162. }  
  163.   
  164. //3.测试动态规划算法非递归实现  
  165. void test_3(string x, string y){  
  166.     //3.1参数处理  
  167.     char result[X+1];  
  168.     int xlen = x.length();  
  169.     int ylen = y.length();  
  170.     int tmp_1[2][Y+1] = {-2};  
  171.     int tmp_2[X+1][Y+1] = {-2};  
  172.     //3.2执行计算  
  173.     int max_len = LCS_length_2(x, y, tmp_1, tmp_2, xlen, ylen);  
  174.     LCS_print_1(x, result, tmp_2, xlen, ylen);  
  175.     //3.3输出结果  
  176.     cout << "3.动态规划法非递归求最长公共子序列:" << endl;  
  177.     cout << "  最大公共子序列长度为:" << max_len << " 序列为:";  
  178.     for(int j = max_len - 1; j >= 0; j--){  
  179.         cout << result[j];  
  180.     }  
  181.     cout << endl;  
  182. }  
  183.   
  184. char* rand_string(char* str, int len){  
  185.     int i = 0;  
  186.     srand((unsigned)time(NULL));  
  187.     for(i = 0; i < len; i++){  
  188.         str[i] = rand()%26 + 'a';  
  189.     }  
  190.     str[i] = '\0';  
  191.     return str;  
  192. }  
  193.   
  194. long getCurrentTime(){  
  195.     struct timeval tv;  
  196.     gettimeofday(&tv, NULL);  
  197.     return tv.tv_sec * 1000 + tv.tv_usec / 1000;  
  198. }  
  199.   
  200. int main()  
  201. {  
  202.     char str_1[X+1];   
  203.     rand_string(str_1,X);  
  204.     string x(str_1);  
  205.       
  206.     sleep(1);  
  207.       
  208.     char str_2[Y+1];  
  209.     rand_string(str_2,Y);  
  210.     string y(str_2);  
  211.       
  212.     cout << "string x = " << x << endl;  
  213.     cout << "  字符串长度为:" << x.length() << endl;  
  214.     cout << "string y = " << y << endl;  
  215.     cout << "  字符串长度为:" << y.length() << endl;  
  216.       
  217.     long time_1 = getCurrentTime();  
  218.     //test_1(x, y);  
  219.     long time_2 = getCurrentTime();  
  220.     cout << "  用时:";  
  221.     cout << time_2 - time_1 << " ms;" << endl;  
  222.       
  223.     long time_3 = getCurrentTime();  
  224.     test_2(x, y);  
  225.     long time_4 = getCurrentTime();  
  226.     cout << "  用时:";  
  227.     cout << time_4 - time_3 << " ms;" << endl;  
  228.   
  229.     long time_5 = getCurrentTime();  
  230.     test_3(x, y);  
  231.     long time_6 = getCurrentTime();  
  232.     cout << "  用时:";  
  233.     cout << time_6 - time_5 << " ms;" << endl;  
  234.       
  235.     return 1;  
  236. }  
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值