#include <stdio.h> #include <string.h> void preKMP(char *pattern, int *prefix, int n) { int len = 0; prefix[0] = 0; for (int i = 1; i < n; i++) { while (len > 0 && pattern[i] != pattern[len]) { len = prefix[len - 1]; } if (pattern[i] == pattern[len]) { len++; } prefix[i] = len; } } void KMP(char *text, char *pattern) { int n = strlen(pattern); int m = strlen(text); int *prefix = malloc(n * sizeof(int)); preKMP(pattern, prefix, n); int j = 0; for (int i = 0; i < m; i++) { while (j > 0 && text[i] != pattern[j]) { j = prefix[j - 1]; } if (text[i] == pattern[j]) { j++; } if (j == n) { printf("Pattern found at index %d ", i - j + 1); j = prefix[j - 1]; } } free(prefix); } int main() { char text[100]; char pattern[100]; printf("Enter the text: "); fgets(text, 100, stdin); printf("Enter the pattern: "); fgets(pattern, 100, stdin); KMP(text, pattern); return 0; }找出以上程序错误并修改
时间: 2023-12-14 19:37:26 浏览: 133
字符串函数string.h应用举例.-综合文档
在程序中,应该先判断输入的字符串是否包含换行符,如果包含则需要将其替换为字符串结束符'\0'。此外,在使用动态分配内存时,需要在程序结束时及时释放内存。
以下是修改后的程序:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void preKMP(char *pattern, int *prefix, int n) {
int len = 0;
prefix[0] = 0;
for (int i = 1; i < n; i++) {
while (len > 0 && pattern[i] != pattern[len]) {
len = prefix[len - 1];
}
if (pattern[i] == pattern[len]) {
len++;
}
prefix[i] = len;
}
}
void KMP(char *text, char *pattern) {
int n = strlen(pattern);
int m = strlen(text);
int *prefix = malloc(n * sizeof(int));
preKMP(pattern, prefix, n);
int j = 0;
for (int i = 0; i < m; i++) {
while (j > 0 && text[i] != pattern[j]) {
j = prefix[j - 1];
}
if (text[i] == pattern[j]) {
j++;
}
if (j == n) {
printf("Pattern found at index %d\n", i - j + 1);
j = prefix[j - 1];
}
}
free(prefix);
}
int main() {
char text[100];
char pattern[100];
printf("Enter the text: ");
fgets(text, 100, stdin);
text[strcspn(text, "\n")] = '\0'; // 替换换行符为'\0'
printf("Enter the pattern: ");
fgets(pattern, 100, stdin);
pattern[strcspn(pattern, "\n")] = '\0'; // 替换换行符为'\0'
KMP(text, pattern);
return 0;
}
```
阅读全文