利用KMP算法求子串在主串中不重叠出现的次数的c语言代码
时间: 2024-02-12 18:45:38 浏览: 72
利用KMP算法进行子串的快速查找
以下是利用KMP算法求子串在主串中不重叠出现的次数的C语言代码:
#include <stdio.h>
#include <string.h>
int KMPSearch(char* pat, char* txt) {
int M = strlen(pat);
int N = strlen(txt);
int i = 0, j = 0, count = 0;
int* lps = (int*)malloc(M * sizeof(int));
computeLPSArray(pat, M, lps);
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
count++;
j = lps[j-1];
}
else if (i < N && pat[j] != txt[i]) {
if (j != 0)
j = lps[j-1];
else
i++;
}
}
free(lps);
return count;
}
void computeLPSArray(char* pat, int M, int* lps) {
int len = 0;
int i = 1;
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[] = "ABCABCDABCABCD";
char pat[] = "ABCD";
printf("The count of non-overlapping occurrences of '%s' is %d", pat, KMPSearch(pat, txt));
return 0;
}
阅读全文