编写程序,实现查找两个字符串中的最长公共子串
可直接运行
//1、编写程序,实现查找两个字符串中的最长公共子串;
//取next数组中
#include <stdio.h>
#include <string.h>
void Next(char *T, int *next)
{
int i = 1;
next[1] = 0;
int j = 0;
while (i < strlen(T))
{
if (j == 0 || T[i - 1] == T[j - 1])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int KMP(char *S, char *T)
{
int next[10];
int changdu,maxcd=0;
Next(T, next); //根据模式串T,初始化next数组
int i = 1;
int j = 1;
while (i <= strlen(S) && j <= strlen(T))
{
//j==0:代表模式串的第一个字符就和当前测试的字符不相等;S[i-1]==T[j-1],如果对应位置字符相等,两种情况下,指向当前测试的两个指针下标i和j都向后移
if (j == 0)
{
i++;
j++;
changdu=0;
}
else if (S[i - 1] == T[j - 1])
{
i++;
j++;
changdu=j;
}
else
{
j = next[j]; //如果测试的两个字符不相等,i不动,j变为当前测试字符串的next值
}
if(changdu>maxcd)
{
maxcd=changdu;
}
}
if (j > strlen(T))
{ //如果条件为真,说明匹配成功
printf("the max length is:%d", strlen(T));
return i - (int)strlen(T);
}
printf("the max length is:%d", maxcd-1);
return -1;
}
int main()
{
int i = KMP("ababcabcacbab", "abcd");
/*if(i != -1)//完全匹配
{
//printf("sucess %d\n", i);
}
*/
return 0;
}