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
|
// Runtime: 4 ms, faster than 99.00% of C++ online submissions for Implement strStr().
// Memory Usage: 7.3 MB, less than 11.26% of C++ online submissions for Implement strStr().
class Solution {
public:
int strStr(string str,string pat){
if(pat=="") return 0;
vector<int> next=get_next(pat);
int j=-1;
for(int i=0;i<str.size();++i){
while(j>-1 && pat[j+1]!=str[i])
j=next[j];
if(pat[j+1]==str[i])
++j;
if(j==pat.size()-1)
return i-pat.size()+1;
}
return -1;
}
private:
vector<int> get_next(string pat){
vector<int> next(pat.size(),-1);
int j=-1;
for(int i=1;i<pat.size();++i){
while(j>-1 && pat[j+1]!=pat[i])
j=next[j];
if(pat[j+1]==pat[i])
++j;
next[i]=j;
}
return next;
}
};
|