KMPmatch 字符串模式匹配

O(m+n)

计算后缀数组时,子串进行的也是模式匹配。

/* KMP match */
# include <stdio.h>
# include <string.h>
# include <stdlib.h>

/* P in T */
int KMPmatch(char *T, char *P)
{
int n, m;
int i, j, k, *next;

n = strlen(T);
m = strlen(P);

next = (int *)malloc((m-1)*sizeof(int));
    /* compute postfix : next[] */
next[0] = -1;
k = -1;
for (i = 1; i < m; ++i)
{
while (k>=0 && P[k+1]!=P[i])
k = next[k];
if (P[k+1] == P[i]) ++k;
next[i] = k;
}

/*
for (i=0; i<m; ++i)
printf("%d ", next[i]+1);
putchar('\n');
*/

/* pattern match */
i = -1;
for (j = 0; j < n; ++j)
{
while (i>=0 && P[i+1]!=T[j])
i = next[i];
if (P[i+1] == T[j]) ++i;
if (i == m-1) return (j-m+1);
/*
if (i == m-1)
{
printf("Pattern occurs with shift: %d\n", j-m+1);
i = next[i];
}
*/
}

return -1;
}

int main()
{
int i;

i = KMPmatch("Heababababcaf", "ababababca");
printf("index in T: %d\n", i);

return 0;
}

strstr的用法:

/* strstr */
# include <stdio.h>
# include <string.h>
int main()
{
char T[] = "Hello, world";
char P[] = "ello, ";
char *ptr;

ptr = strstr(T, P);
if (ptr != NULL) printf("%d %c\n", ptr-T, *ptr);
else printf("dismatch\n");

return 0;
}



原文地址:https://www.cnblogs.com/JMDWQ/p/2360539.html