最长公共子串

  (华中科技大学机试题)给定任意俩组字符串S1 和S2,请编程输出他们间的最大相同子串。例如:S1=12abc78,
S2=7bc2,则输出为:bc

#include <stdio.h>
#include <string.h>

void LargestCommonSubStr(char *str1,char *str2);
int main()
{
    char str1[128] = {''} ,str2[128] = {'
'};
    printf("请输入第一个字符串
");
    scanf("%s",str1);
    printf("请输入第二个字符串
");
    scanf("%s",str2);
    strlen(str1) > strlen(str2)?LargestCommonSubStr(str1,str2):LargestCommonSubStr(str2,str1);
    return(0);
}

void LargestCommonSubStr(char *longer,char *shorter)
{
    int start,len,shortlen;
    bool found = false;                //最长标记,记得初始胡
    char buff[128] = {''};        //缓冲区,并且初始化
    shortlen = strlen(shorter);
    for(len = shortlen;len > 0 ; len--)    //开始遍历,从最长到最短
    {
        for(start = 0; start <= shortlen - len; start++)
        {
            strncpy(buff,shorter+start,len);
            if(strstr(longer,buff)!=NULL)
            {
                printf("最长公共子串为:%s
",buff);
                found = true;                //标记已经找到最长
            }
            memset(buff,'',sizeof(buff));
        }
        if(found)                            //当出现最长的时候,跳出循环
            break;
    }
}
原文地址:https://www.cnblogs.com/houjun/p/6507690.html