forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementstrStr.cpp
More file actions
38 lines (37 loc) · 888 Bytes
/
ImplementstrStr.cpp
File metadata and controls
38 lines (37 loc) · 888 Bytes
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
class Solution {
public:
int strStr(char *haystack, char *needle) {
int n = strlen(needle);
if(n==0) {
return 0;
}
int* next = new int[n];
int i=-1;
int j=0;
next[0] = -1; // if mismatch at needle[0], then make current array index align with needle[-1]
while(j<n-1) {
if( i<0 || needle[j] == needle[i]) {
j++;
i++;
next[j] = i;
} else {
i = next[i];
}
}
int n1 = strlen(haystack);
j=0;
i=0;
while(j<n1 && i<n) {
if( i<0 || haystack[j] == needle[i]) {
i++;
j++;
} else {
i = next[i];
}
}
if(i==n){
return j-n;
}
return -1;
}
};