#include <stdio.h>
#include <string.h>
void print_table(char *str1,char *str2,int **pf)
{
int i,j,row,col;
row = strlen(str1);
col = strlen(str2);
printf("\t\t");
for (i=0; i<col; i++)
printf("%c\t",str2[i]);
for (i=0; i<=row; i++)
{
for (j=0; j<=col; j++)
{
if (j == 0)
{
printf("\n");
if (i)
printf("%c\t",str1[i-1]);
else
printf("\t");
}
printf("%d\t",pf[i][j]);
}
}
}
int commstr(char *str1, char *str2)
/* 返回str1,str2的最长公共之串长度*/
{
int len1=strlen(str1),len2=strlen(str2),row,col,max=0;
int **pf = new int*[len1+1];//动态分配一个二维数组作为辅助空间
for (row=0; row<len1+1; row++)
pf[row] = new int[len2+1];
//数组赋初值
for (row=0; row<len1+1; row++)
pf[row][0] = 0;
for (col=0; col<len2+1; col++)
pf[0][col] = 0;
for (row=1; row<=len1; row++)
for (col=1;col<=len2; col++)
{
if (str1[row-1] == str2[col-1])
{
pf[row][col] = pf[row-1][col-1] + 1;
max = pf[row][col] > max ? pf[row][col] : max;
}
else
pf[row][col] = 0;
}
print_table(str1,str2,pf);
//空间回收
for (row=0; row<len1+1; row++)
delete[] pf[row];
delete[] pf;
return max;
}
int main(int argc,char **argv)
{
if (argc >= 3)
{
printf("String:\n\t1. %s\n\t2. %s\n",argv[1],argv[2]);
printf("\nmax substr length:%d\n",commstr(argv[1],argv[2]));
}
else
{
printf("Usage : %s string1 string2 \n", argv[0]);
}
return 0;
}
|