源码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
#define DEBUG_SWITCH 1
#if DEBUG_SWITCH
#define DEBUG_INFO(format, ...) printf("LINE: %d: "format"\n", __LINE__, ##__VA_ARGS__)
#else
#define DEBUG_INFO(format, ...)
#endif
#define TRUE 1
#define FALSE 0
#define UINT64_MAX (0XFFFFFFFFFFFFFFFF)
#define UINT32_MAX (0XFFFFFFFF)
#define UINT16_MAX (0XFFFF)
#define UINT8_MAX (0XFF)
typedef unsigned char uint8_t;
typedef signed char sint8_t;
typedef unsigned short int uint16_t;
typedef unsigned long int uint32_t;
typedef signed long int sint32_t;
typedef unsigned long long int uint64_t;
#define GET_ARR_SIZE(arr,type) (sizeof(arr)/sizeof(type))
#define GET_STR_LEN(str) (sizeof(str)-1)
void get_next(const char *p, sint32_t *next, sint32_t next_len)
{
sint32_t i = 0;
sint32_t j = -1;
next[0] = -1;
while (i < (next_len - 1))
{
if ((j == -1) || (p[i] == p[j]))
{
++i;
++j;
if (p[i] != p[j])
{
next[i] = j;
}
else {
next[i] = next[j];
}
}
else
{
j = next[j];
}
}
}
sint32_t kmp(char *t, sint32_t t_len, char *p, sint32_t *next, sint32_t next_len)
{
sint32_t i = 0;
sint32_t j = 0;
if ((t == NULL) || (p == NULL) || (t_len < next_len))
{
return -1;
}
else
{
}
get_next(p, next, next_len);
while ((i < t_len) && (j < next_len))
{
if ((j == -1) || (t[i] == p[j]))
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (j == next_len)
{
return (i - next_len);
}
else
{
return -1;
}
}
int main()
{
char arr[] = "abaabcdabcab";
char brr[] = "cab";
sint32_t next[GET_STR_LEN(brr)] = { 0 };
printf("%d\n", kmp(arr, GET_STR_LEN(arr), brr, next, GET_STR_LEN(brr)));
return 0;
}
验证
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/32958efd3e2bfe582d4d12e4efaf777d.png)