-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0028.cpp
More file actions
executable file
·39 lines (34 loc) · 773 Bytes
/
LC0028.cpp
File metadata and controls
executable file
·39 lines (34 loc) · 773 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
39
/*
Problem Statement: https://leetcode.com/problems/implement-strstr/
Time: O(n + m)
Space: O(m)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
int strStr(string& haystack, string& needle) {
int n = haystack.size(), m = needle.size();
// base case
if (needle.empty())
return 0;
vector<int> pi(m);
// prefix function
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle[i] != needle[j])
j = pi[j - 1];
if (needle[i] == needle[j])
j++;
pi[i] = j;
}
// knuth-morris-pratt algorithm
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack[i] != needle[j])
j = pi[j - 1];
if (haystack[i] == needle[j])
j++;
if (j == m)
return i - m + 1;
}
return -1;
}
};