0%

KMP

haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)

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
class Solution {
public:
int strStr(string haystack, string needle) {
if(!needle.length()) return 0;
int* next=new int[needle.length()];
Creatnext(next,needle);
int j=-1;
for(size_t i=0;i<haystack.length();++i)
{
while(haystack[i]!=needle[j+1]&&j>=0)
j=next[j];
if(haystack[i]==needle[j+1])
++j;
if(j==(int)needle.length()-1)
{
delete []next;
return i-needle.length()+1;
}
}
delete []next;
return -1;
}
private:
void Creatnext(int* next,const string& s)
{
int j=-1;
next[0]=j;
for(string::size_type i=1;i<s.length();++i)
{
while(j>=0&&s[i]!=s[j+1])
j=next[j];
if(s[i]==s[j+1])
++j;
next[i]=j;
}
}
};