-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
64 lines (54 loc) · 956 Bytes
/
Copy pathKMP.cpp
File metadata and controls
64 lines (54 loc) · 956 Bytes
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <cstring>
using namespace std;
char P[10002];
char T[1000002];
int NEXT[10002];
void CalNext()
{
NEXT[0] = -1;
int len = strlen(P),i = 0,j = -1;
while(i < len)
{
if(j == -1 || P[i] == P[j])
{
NEXT[++ i] = ++j;
// printf("%d:%d, ", i - 1, NEXT[i]);
}
else
j = NEXT[j];
}
// NEXT[len] = 0;
// printf("%d:%d, ", len - 1, NEXT[len]);
}
int find()
{
int ans = 0, i = 0, j = 0, len0 = strlen(P), len = strlen(T);
while(i < len)
{
if(j == -1 || T[i] == P[j])
{
i ++;
j ++;
}
else
{
j = NEXT[j];
}
if(j == len0)
ans ++;
}
return ans;
}
int main()
{
int N;
scanf("%d", &N);
while(N --)
{
scanf("%s %s", P, T);
CalNext();
printf("%d\n", find());
}
return 0;
}