-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode-28-KMP.cpp
57 lines (57 loc) · 1.17 KB
/
leetcode-28-KMP.cpp
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
class Solution {
public:
int strStr(string haystack, string needle) {
int n=haystack.length();
int m=needle.length();
if(!m)
{
return 0;
}
vector<int> lps=KMPprocessing(needle);
for(int i=0,j=0;i<n;)
{
if(haystack[i]==needle[j])
{
i++;
j++;
}
if(j==m)
{
return i-j;
}
if(i<n&&haystack[i]!=needle[j])
{
if(j)
{
j=lps[j-1];
}
else
i++;
}
}
return -1;
}
private:
vector<int> KMPprocessing(string& needle)
{
int n=needle.length();
vector<int> lps(n,0);
int len;
for(int i=1,len=0;i<n;)
{
if(needle[i]==needle[len])
{
lps[i++] = ++len;
}
else if(len)
{
len=lps[len-1];
}
else
{
lps[i++]=0;
}
}
return lps;
}
};