1. 程式人生 > >兩組字符串中的最長公共子串(可包含多個長度相同的最長公共子串)

兩組字符串中的最長公共子串(可包含多個長度相同的最長公共子串)

String

#include <stdio.h>
#include <string.h>
main()
{
int i,j,k,n,h,m=0,count=0,count1=0,count2=0,count3=0;
char str1[100], str2[100];
int str3[100];

printf("str1:");
gets(str1);
printf("str2:");
gets(str2);

for(h=0;str1[h]!=‘\0‘;h++){
    for(i=0;str2[i]!=‘\0‘;i++){
        count=0;
        for(j=h,k=i;str1[j]==str2[k] && str1[j]!=‘\0‘ && str2[k]!=‘\0‘;j++,k++){
            count++;
            if(count1<=count){
                count1=count;
                n=j;                    
            }
        }
    }   
}
printf("count1=%d\n",count1);
for(j=n-count1+1;j<=n;j++){
    printf("%c ",str1[j]);
}   
printf("\n");

for(h=0;str1[h]!=‘\0‘;h++){
    for(i=0;str2[i]!=‘\0‘;i++){
        count=0;
        for(j=h,k=i;str1[j]==str2[k] && str1[j]!=‘\0‘ && str2[k]!=‘\0‘;j++,k++){
            count++;
            if(count1==count){
                str3[m]=j;
                m++;
                count3++;
                count=0;
            }
        }
    }   
}
printf("count3=%d\n",count3);
for(m=0;m<count3;m++){
    for(i=str3[m]-count1+1;i<=str3[m];i++){
        printf("%c ",str1[i]);
    }
    printf("\n");
}   
printf("\n");

}

兩組字符串中的最長公共子串(可包含多個長度相同的最長公共子串)