最長公共子串

#include <stdlib.h>
#include <stdio.h>

#define MAX 10

int comMatrix[MAX][MAX];
char comstr[MAX];

char *commonString(char string1[], char string2[])
{
    int len1=0,len2=0;
    int flag=0;
    int max=0;
    int i, j;

    while(string1[len1]!='\0') len1++;
    while(string2[len2]!='\0') len2++;

    for(i=0;i<len1;i++)
    {
        for(j=0;j<len2;j++)
        {
            if(string1[i]==string2[j]) comMatrix[i][j]=1;
            else comMatrix[i][j]=0;

            if(i>0&&j>0&&comMatrix[i][j]==1) comMatrix[i][j]+=comMatrix[i-1][j-1];

            if(comMatrix[i][j]>=max)
            {
                max=comMatrix[i][j];
                flag=j;
            }
        }

    }

    for(i=0,j=flag-max+1;j<=flag;i++,j++)
    {
        comstr[i]=string2[j];
    }
    comstr[max]='\0';

    return comstr;
}


int main()
{
    char *A="aomcdf", *B="pmcdfa";

    printf("%s\n", commonString(A, B));
}

 將字符串問題轉化爲矩陣問題,而且在矩陣構造過程當中求解spa

相關文章
相關標籤/搜索