子字符串和子串是有区别的,字符串要求是连续的,而子串则不用连续。
求最长公共子字符串的问题也可以用类似于求最长公共子串中矩阵递推的方法,但是需要注意的是,当两个字符串中某个位置字符不同时,需要将相应矩阵位置设为0.
定义f(m, n)为Xm和Yn之间最长的子字符串的长度并且该子字符串结束于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)就是解。
- #include "stdafx.h"
- #include "iostream"
- using namespace std;
- int conLCS(char *str1,char *str2)
- {
- if(str1==NULL||str2==NULL)
- return 0;
- int length1=strlen(str1);
- int length2=strlen(str2);
- if(length1==0||length2==0)
- return 0;
- int **LSC_length=new int*[length1];
- for(int i=0;i<length1;i++)
- {
- LSC_length[i]=new int[length2];
- memset(LSC_length[i],0,sizeof(int)*length2);
- }
- int maxlength=0;
- int pos=0;
- for(int i=0;i<length1;i++)
- for(int j=0;j<length2;j++)
- {
- if(i==0||j==0)
- {
- if(str1[i]==str2[j])
- {
- LSC_length[i][j]=1;
- if(maxlength==0)
- {maxlength=1;
- pos=i;}
- }
- else
- LSC_length[i][j]=0;
- }
- else if(str1[i]==str2[j])
- {
- LSC_length[i][j]=LSC_length[i-1][j-1]+1;
- if(maxlength<LSC_length[i][j])
- {
- maxlength=LSC_length[i][j];
- pos=i;
- }
- }
- else
- {
- LSC_length[i][j]=0;
- }
- }
- for(int k=pos-maxlength+1;k<=pos;k++)
- cout<<str1[k];
- return maxlength;
- }
- int main(int argc, char* argv[])
- {
- char *a="BDCABA";
- char *b="ABCBDAB";
- cout<<conLCS(a,b)<<endl;;
- return 0;
- }