1. 程式人生 > >最長的公共子串

最長的公共子串

char base1[9]={'1','A','B','2','3','4','5','C','D'};
char base2[7]={'1','2','3','4','5','E','F'};
int longestCountinue()
{
    int dp[9][7]={{0},{0}};
    int i,j;
    for(i=0;i<9;i++)
    {
        if(base1[i] == base2[0])
        {
            dp[i][0] = 1;
        }
    }

    for(j=1;j<7;j++)
    {
        if
(base2[j] == base1[0]) { dp[0][j] = 1; } } /*dp[i][j]的含義是以base[i]和base2[j]為結尾的最大公共子串*/ for(i=1;i<9;i++) { for(j=1;j<7;j++) { if(base1[i] == base2[j]) { dp[i][j] = dp[i-1][j-1] +1; } } } for
(i=0;i<9;i++) { printf("\r\n"); for(j=0;j<7;j++) { printf("%d ",dp[i][j]); } } /*找到最大值的下標*/ int max = dp[0][0]; int m = 0,n=0; printf("\r\n"); for(i=0;i<9;i++) { for(j=0;j<7;j++) { if(dp[i][j] > max) { max = dp[i][j]; m
=i; n=j; printf("%d ",max); } } } printf("\r\nm:%d.n:%d ",m,n); i=m; int index = 4; char res[4] ={0}; while(i>=0) { res[--index] = base1[i--]; } char *p1; p1 = res; printf("%s",p1); return 0; } /* 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 4 m:6.n:4 2345 */ int longestCountinue2() { int i,j,m=0,n=0; int row = 9; int len = 0; int max = 0; i=0; j=6;//定位到最右上角 int f; while(i<row) { m = i; n=j; while(m<9 && n<7) { if(base1[m] == base2[n]) { len ++; if(max<len) { max =len; f = m; printf("max :%d ",max); } } else { len = 0; } m++; n++; } if(j>0) { j--; } if(j==0) { i++; } } int res = f-max + 1; printf("\r\n"); for(i=0;i<max;i++) { printf("%c ",base1[res++]); } return 0; }