给出KMP算法及其改进算法的C++实现
时间: 2023-11-10 11:16:42 浏览: 94
以下是KMP算法及其改进算法(优化next数组)的C语言实现:
KMP算法:
```c
void getNext(char *pattern, int *next) {
int i = 0, j = -1;
next[0] = -1;
while (pattern[i]) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int KMP(char *text, char *pattern) {
int i = 0, j = 0;
int text_len = strlen(text);
int pattern_len = strlen(pattern);
int *next = (int *)malloc(sizeof(int) * pattern_len);
getNext(pattern, next);
while (i < text_len && j < pattern_len) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j]; }
}
free(next);
if (j == pattern_len) {
return i - j;
} else {
return -1;
}
}
```
改进算法(优化next数组):
```c
void getOptimizedNext(char *pattern, int *next) {
int i = 0, j = -1;
next[0] = -1;
while (pattern[i]) {
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_Optimized(char *text, char *pattern) {
int i = 0, j = 0;
int text_len = strlen(text);
int pattern_len = strlen(pattern);
int *next = (int *)malloc(sizeof(int) * pattern_len);
getOptimizedNext(pattern, next);
while (i < text_len && j < pattern_len) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
}
free(next);
if (j == pattern_len) {
return i - j;
} else {
return -1;
}
}
```
在上面的示例代码中,KMP算法中的getNext函数用来计算next数组,KMP函数用来执行KMP算法的主体部分。改进算法中的getOptimizedNext函数用来计算优化后的next数组,KMP_Optimized函数用来执行优化后的KMP算法。这些函数可以根据需要修改函数参数和返回值类型以适应实际情况。
阅读全文