-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImplementStrStr.cc
56 lines (41 loc) · 1015 Bytes
/
ImplementStrStr.cc
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
#include "leet.h"
#include <stdio.h>
#include <algorithm>
#include <cstring>
class Solution{
public:
int strStr(string txt, string pat) {
int lent = txt.length();
int lenp = pat.length();
int fail[lenp + 2];
fail[0] = -1;
for (int i = 1; i < lenp; ++i) {
int k = fail[i - 1];
for (k = fail[i - 1]; k >=0 && pat[k + 1] != pat[i]; k = fail[k]);
fail[i] = (pat[k + 1] == pat[i]) ? (k + 1) : -1;
}
int i, k;
for (i = 0, k = 0; i < lent && k < lenp;) {
if (txt[i] == pat[k]) {
++i; ++k;
} else if (0 == k){
++i;
} else {
k = fail[k - 1] + 1;
}
}
if (k >= lenp) {
return i - k;
} else {
return -1;
}
}
};
int main(){
Solution slu;
string s, t;
while (cin >> s >> t) {
cout << slu.strStr(s, t) << endl;
}
return 0;
}