-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmpall.c
40 lines (40 loc) · 1007 Bytes
/
kmpall.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
if (argc != 3) return 1;
unsigned s_length = strlen(argv[1]);
unsigned t_length = strlen(argv[2]);
unsigned *p = calloc(s_length + t_length + 1, sizeof(unsigned));
if (p == NULL) return 2;
char *tmp_ptr = calloc(s_length + t_length + 2, sizeof(char));
if (tmp_ptr == NULL)
{
free(p);
return 2;
}
strcpy(tmp_ptr, argv[1]);
argv[1] = tmp_ptr;
argv[1][s_length] = (char)31;
strcat(argv[1], argv[2]);
unsigned k = 0;
for (unsigned i = 1; i != s_length + t_length + 1; ++i)
{
while (k > 0 && argv[1][i] != argv[1][k])
{
k = p[k-1];
}
if (argv[1][i] == argv[1][k])
{
++k;
}
p[i] = k;
if (p[i] == s_length)
{
printf("%u ", i - 2 * s_length);
}
}
free(p);
free(tmp_ptr);
}