子字符串和子串是有区别的,字符串要求是连续的,而子串则不用连续。

求最长公共子字符串的问题也可以用类似于求最长公共子串中矩阵递推的方法,但是需要注意的是,当两个字符串中某个位置字符不同时,需要将相应矩阵位置设为0.

定义f(m, n)XmYn之间最长的子字符串的长度并且该子字符串结束于Xm & Yn。因为要求是连续的,所以定义f的时候多了一个要求字符串结束于Xm & Yn

 

如果xm != yn, f(m, n) = 0

如果xm = yn, f(m, n) = f(m-1, n-1) + 1

因为最长字符串不一定结束于Xm / Yn末尾,所以这里必须求得所有可能的f(p, q) | 0 < p < m, 0 < q < n, 最大的f(p, q)就是解。

 

 
  
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4.  
  5. int conLCS(char *str1,char *str2)  
  6. {  
  7.     if(str1==NULL||str2==NULL)  
  8.         return 0;  
  9.     int length1=strlen(str1);  
  10.     int length2=strlen(str2);  
  11.     if(length1==0||length2==0)  
  12.         return 0;  
  13.     int **LSC_length=new int*[length1];  
  14.     for(int i=0;i<length1;i++)  
  15.     {  
  16.         LSC_length[i]=new int[length2];  
  17.         memset(LSC_length[i],0,sizeof(int)*length2);  
  18.     }  
  19.  
  20.     int maxlength=0;  
  21.     int pos=0;  
  22.     for(int i=0;i<length1;i++)  
  23.         for(int j=0;j<length2;j++)  
  24.         {  
  25.             if(i==0||j==0)  
  26.             {  
  27.                 if(str1[i]==str2[j])  
  28.                 {  
  29.                     LSC_length[i][j]=1;  
  30.                     if(maxlength==0)  
  31.                     {maxlength=1;  
  32.                     pos=i;}  
  33.                 }  
  34.                 else 
  35.                     LSC_length[i][j]=0;  
  36.             }  
  37.             else if(str1[i]==str2[j])  
  38.             {  
  39.                 LSC_length[i][j]=LSC_length[i-1][j-1]+1;  
  40.                 if(maxlength<LSC_length[i][j])  
  41.                 {  
  42.                     maxlength=LSC_length[i][j];  
  43.                     pos=i;  
  44.  
  45.                 }  
  46.                   
  47.             }  
  48.           
  49.             else 
  50.             {  
  51.                 LSC_length[i][j]=0;  
  52.                   
  53.             }  
  54.         }  
  55.         for(int k=pos-maxlength+1;k<=pos;k++)  
  56.             cout<<str1[k];  
  57.         return maxlength;  
  58. }  
  59.  
  60.  
  61.  
  62.  
  63. int main(int argc, char* argv[])  
  64. {  
  65.     char *a="BDCABA";  
  66.     char *b="ABCBDAB";  
  67.     cout<<conLCS(a,b)<<endl;;  
  68.     return 0;  
  69. }