KMPmatch 字符串模式匹配

O(m+n)

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

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

/* 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 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
# 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/archive/2012/02/20/2360539.html

你可能感兴趣的:(KMPmatch 字符串模式匹配)