求两个字符串的公共连续子序列

来源:互联网 发布:mac上传图片 编辑:程序博客网 时间:2024/06/05 19:09

这与求两个字符串的公共子序列要区分开,见http://blog.csdn.net/shandianling/article/details/7888050<br/>
但 求你方法与求公共子序列类似,而且要简单一点。<br/>
方法:动态规划.
循环遍历两个字符串,查找当s1[i]==s2[k] 的情况 然后保存在c[i][k]中,c[i][k]=c[i-1][k-1]+1 最后我们会得到类似以下矩阵

 
OK,结果可以看出来了。

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4. //求公共子串(连续),注意跟求公共子序列有区别  
  5. int lcstr( const char* s1,const char* s2)  
  6. {  
  7.     //clen保存公共子串的最大长度,s1_Mindex保存 s1公共子串的最后一个元素的位置  
  8.     int len1,len2,i,k,cLen=1,s1_Mindex=0;  
  9.     int **c;  
  10.     if(s1==NULL || s2==NULL) return -1;  
  11.     len1=strlen(s1);  
  12.     len2=strlen(s2);  
  13.     if(len1< 1 || len2 < 1) return -1;  
  14.     c=malloc(sizeof(int*)*len1);  
  15.     for(i=0;i<len1;i++)  
  16.     {  
  17.         c[i]=(int *)malloc(len2*sizeof(int));  
  18.         memset(c[i],0,len2*sizeof(int));  
  19.     }  
  20.     /**********init end!*************/  
  21.     for(i=0;i<len1;i++)  
  22.     {  
  23.         for(k=0;k<len2;k++)  
  24.         {  
  25.             if(i==0 || k==0)  
  26.             {  
  27.                 if(s1[i]==s2[k]) c[i][k]=1;  
  28.                 else c[i][k]=0;  
  29.             }  
  30.             else  
  31.             {  
  32.                 if (s1[i] == s2[k])  
  33.                 {  
  34.                     c[i][k] = c[i - 1][k - 1] + 1;  
  35.                     if (cLen < c[i][k])  
  36.                     {  
  37.                         cLen = c[i][k];  
  38.                         s1_Mindex = i;  
  39.                     }  
  40.                 }  
  41.             }  
  42.         }  
  43.     }  
  44.     //*************//  
  45.     // printf the one of lcs 只是其中一条,如果存在多条。  
  46.     for(i=0;i<cLen;i++)  
  47.     {  
  48.         printf("%c",*(s1+s1_Mindex-cLen+1+i));  
  49.     }  
  50.     /*****free array*************/  
  51.     for(i=0;i<len1;i++)  
  52.         free(c[i]);  
  53.     free(c);  
  54.     return cLen;  
  55.   
  56. }  
  57. int main(void) {  
  58.     char a[]="abcgooglecba";  
  59.     char b[]="cbagoogleABVC";  
  60.     printf("\nlcstr = %d\n",lcstr(a,b));  
  61.     return 0;  
  62. }  
阅读全文
0 0