#include
#include
#include
/*************************************************
*函数功能:将制定的字符串中的next值放入一个数组中
*参 数:str为字符串,next为数字数组
*返 回:无
*说 明:改函数实际是将target串于自己中的子字符串匹配,
* 计算target中的字符不匹配时的回溯值。
**************************************************/
void get_next(char *str, int *next)
{
int i = 1;
int j = -1;
/*与第一个字符不匹配,就不进行回溯,直接与下一个进行匹配*/
next[0] = -1;
for (i = 0, j = -1; i < strlen(str);)
{
if ((j == -1) || (str[i] == str[j]))
{
//匹配相同或者是与第一个都不匹配
i++;
j++;
next[i] = j;
}
else
{
//匹配不相同,进行回溯
j = next[j];
}
}
return ;
}
/*********************************************************
*函数功能:在主串中匹配已有的子串
*参 数:source是主串,target是子字符串
*返 回:成功返回子串在主串中的位置,失败返回-1
*说 明:kmp算法较传统的匹配算法在一些特定场合可以提高效率。
**********************************************************/
int my_match(char *source, char *target)
{
int source_len = strlen(source);
int target_len = strlen(target);
int i = 0;
int j = 0;
int *next = NULL;
next = (int *)malloc(target_len);
if (next == NULL)
{
printf("malloc memory is failed! /n");
return -1;
}
get_next(target, next);
for (i = 0, j = 0; (i < source_len) && (j < target_len);)
{
if ((j == -1) || (source[i] == target[j]))
{
i++;
j++;
}
else
{
j = next[j];
}
}
free(next);
if (j >= target_len)
{
//返回字串在主串中的第sum个位置
return (i - target_len + 1);
}
else
{
return -1;
}
}
int main()
{
char *source = "abcabcabdccd";
char *target = "abcabd";
int sum = 0;
sum = my_match(source, target);
printf("%d/n", sum);
getch();
return 0;
}
在dev-cpp下编译通过。
本文介绍了一种改进的字符串匹配算法——KMP算法。该算法通过预处理目标字符串,计算出一个辅助数组,避免了传统匹配算法中出现的部分重复比较过程,从而提高了匹配效率。文章给出了完整的C语言实现代码,并通过一个示例展示了如何使用该算法来查找一个字符串在另一个字符串中的位置。

1万+

被折叠的 条评论
为什么被折叠?



