-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
67 lines (54 loc) · 851 Bytes
/
KMP.cpp
File metadata and controls
67 lines (54 loc) · 851 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
#include <iostream>
using namespace std;
int* preProcess(string s) {
int* LPS = new int[s.size()];
LPS[0] = 0;
int pos = 1;
int len = 0;
while (pos < s.size()) {
if (s[len] == s[pos]) {
LPS[pos] = len+1;
len++;
pos++;
}
else {
if (len == 0) {
LPS[pos] = 0;
pos++;
len=0;
}
else {
len = LPS[len - 1];
}
}
}
return LPS;
}
int find(string s, string pattern) {
int* LPS = preProcess(pattern);
int pos1 = 0, pos2 = 0;
while (pos1 < s.size() && pos2 < pattern.size()) {
if (s[pos1] == pattern[pos2]) {
pos1++;
pos2++;
}
else {
if (pos2 == 0) {
pos1++;
}
else {
pos2 = LPS[pos2 - 1];
}
}
}
if (pos1 == pattern.size())
return pos1 - pattern.size();
else
return -1;
}
int main()
{
string s1,s2;
cin >> s1>>s2;
cout << find(s1, s2);
}