kmp算法用c代码实现
时间: 2023-09-11 22:04:42 浏览: 91
c kmp算法实现
3星 · 编辑精心推荐
以下是KMP算法的C语言实现:
```c
#include <stdio.h>
#include <string.h>
void computeLPSArray(char* pat, int M, int* lps); //计算lps数组的函数
void KMPSearch(char* pat, char* txt)
{
int M = strlen(pat);
int N = strlen(txt);
int lps[M];
computeLPSArray(pat, M, lps); //计算lps数组
int i = 0; //txt中的指针
int j = 0; //pat中的指针
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
printf("Found pattern at index %d\n", i - j);
j = lps[j - 1];
}
else if (i < N && pat[j] != txt[i]) {
if (j != 0)
j = lps[j - 1];
else
i++;
}
}
}
void computeLPSArray(char* pat, int M, int* lps)
{
int len = 0;
int i = 1;
lps[0] = 0; //lps[0] 总是0
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else {
if (len != 0) {
len = lps[len - 1];
}
else {
lps[i] = 0;
i++;
}
}
}
}
int main()
{
char txt[] = "ABABDABACDABABCABAB";
char pat[] = "ABABCABAB";
KMPSearch(pat, txt);
return 0;
}
```
输出结果为:
```
Found pattern at index 10
```
阅读全文