Implement strStr() (Easy)

Description

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Analysis

判断子串在父串中出现的第一个位置。直接kmp一下就行了

My Solution

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
//C++
class Solution {
void getnext(char *t,vector<int> &nxt){
int tlen = strlen(t),i=0,j=-1;
nxt.push_back(-1);
while(i<tlen){
if(j==-1||t[i]==t[j]){
i++,j++;
if(t[i]!=t[j])
nxt.push_back(j);
else
nxt.push_back(nxt[j]);
}
else
j = nxt[j];
}
}
public:
int strStr(char *haystack, char *needle) {
vector<int> nxt;
nxt.clear();
getnext(needle,nxt);
int slen = strlen(haystack),tlen = strlen(needle);
int i = 0,j=0;
while(i<slen&&j<tlen){
if(j==-1||needle[j]==haystack[i]){
i++,j++;
}
else{
j = nxt[j];
}
}
if(j>=tlen)
return i-tlen;
return -1;
}
};