-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmp.cpp
More file actions
72 lines (70 loc) · 898 Bytes
/
Copy pathkmp.cpp
File metadata and controls
72 lines (70 loc) · 898 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
65
66
67
68
69
70
71
72
#include <bits/stdc++.h>
using namespace std;
vector<int> psa(string pattern)
{
int m = pattern.length();
vector<int> arr(m);
int i = 0;
int j = 1;
while (j < m)
{
if (pattern[j] == pattern[i])
{
arr[j++] = ++i;
}
else
{
while (i)
{
i = arr[i - 1];
if (pattern[i] == pattern[j])
break;
}
if (pattern[j] == pattern[i])
{
arr[j++] = ++i;
}
else
{
arr[j++] = 0;
}
}
}
return arr;
}
int main()
{
string text, pattern;
cin >> text >> pattern;
int n = text.length();
int m = pattern.length();
vector<int> arr = psa(pattern);
int i = 0, j = 0;
int count = 0;
while (i < n)
{
if (j == m)
{
count++;
j = arr[j - 1];
continue;
}
if (text[i] == pattern[j])
{
i++, j++;
}
else
{
if (j)
j = arr[j - 1];
else
i++;
}
}
if (j == m)
{
count++;
j = arr[j - 1];
}
cout << count;
}