使用C++实现kmp算法
时间: 2023-09-11 18:04:46 浏览: 106
c++ 实现KMP算法
以下是使用C语言实现KMP算法的示例代码:
```c
#include<stdio.h>
#include<string.h>
void getNext(char* pattern, int* next) {
int i = 0, j = -1;
next[0] = -1;
int len = strlen(pattern);
while (i < len - 1) {
if (j == -1 || pattern[i] == pattern[j]) {
++i;
++j;
if (pattern[i] != pattern[j]) {
next[i] = j;
} else {
next[i] = next[j];
}
} else {
j = next[j];
}
}
}
int kmp(char* text, char* pattern) {
int len1 = strlen(text);
int len2 = strlen(pattern);
int* next = (int*)malloc(len2 * sizeof(int));
getNext(pattern, next);
int i = 0, j = 0;
while (i < len1 && j < len2) {
if (j == -1 || text[i] == pattern[j]) {
++i;
++j;
} else {
j = next[j];
}
}
free(next);
if (j == len2) {
return i - j;
} else {
return -1;
}
}
int main() {
char text[100], pattern[100];
printf("Enter the text string: ");
scanf("%s", text);
printf("Enter the pattern string: ");
scanf("%s", pattern);
int pos = kmp(text, pattern);
if (pos == -1) {
printf("The pattern string is not found in the text string.\n");
} else {
printf("The pattern string is found in the text string at position %d.\n", pos);
}
return 0;
}
```
在上述代码中,getNext函数用于计算模式串的next数组,kmp函数用于在文本串中查找模式串。该代码使用了动态内存分配来分配next数组,使用了字符串库中的strlen函数来计算字符串的长度。
阅读全文