-
Notifications
You must be signed in to change notification settings - Fork 0
/
28. Implement strStr().cpp
55 lines (49 loc) · 1.24 KB
/
28. Implement strStr().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
/*
Problem Description:
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
*/
class Solution {
public:
int strStr(string haystack, string needle) {
int i=1,j=1;
vector<int> nextval(needle.size()+1,0);
get_nextval(needle,nextval);
while(i<=haystack.size() && j<=needle.size())
{
if(j==0 || haystack[i-1]==needle[j-1])
{
++i;++j;
}
else
{
j=nextval[j];
}
}
return j>needle.size()?i-needle.size()-1:-1;
}
void get_nextval(string T,vector<int>& nextval)
{
//求模式串T的next函数修正值并存入数组nextval
int i=1,j=0;
nextval[1]=0;
while(i<T.size())
{
if(j==0 || T[i-1]==T[j-1])
{
++i;++j;
nextval[i]=(T[i-1]!=T[j-1]?j:nextval[j]);
}
else
{
j=nextval[j];
}
}
}
};