-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement strStr().cpp
More file actions
39 lines (38 loc) · 1.1 KB
/
Implement strStr().cpp
File metadata and controls
39 lines (38 loc) · 1.1 KB
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
class Solution {
public:
void ComputePrefix(char *p, vector<int> &prefix)
{
int length=strlen(p);
prefix[1]=0;
int longest=0;
for(int i=2;i<=length;i++)
{
while(longest>0&&p[longest]!=p[i-1])
longest=prefix[longest];
if(p[longest]==p[i-1])
longest++;
prefix[i]=longest;
}
}
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> prefix;
int len1=strlen(haystack), len2=strlen(needle);
if(len2==0)
return haystack;
prefix.resize(len2+1);
ComputePrefix(needle, prefix);
int match=0;
for(int i=1;i<=len1;i++)
{
while(match>0&&needle[match]!=haystack[i-1])
match=prefix[match];
if(needle[match]==haystack[i-1])
match++;
if(match==len2)
return haystack+i-len2;
}
return NULL;
}
};