Skip to content

Commit 2b94424

Browse files
committed
add strStr.cpp
1 parent fb49e4e commit 2b94424

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

C++/strStr.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Time Complexity: O(m + n)
2+
// Space Complexity: O(n)
3+
4+
class Solution {
5+
public:
6+
char *strStr(char *haystack, char *needle) {
7+
string target(haystack);
8+
string pattern(needle);
9+
10+
if(target.size() < pattern.size())
11+
return nullptr;
12+
13+
if(pattern.size() == 0)
14+
return haystack;
15+
16+
int i = kmp(target, pattern);
17+
18+
return (i != -1)? haystack + i : nullptr;
19+
}
20+
private:
21+
int kmp(const string &target, const string &pattern) {
22+
const auto m = target.size();
23+
const auto n = pattern.size();
24+
25+
vector<int> failure(n, -1);
26+
for(int i = 1, j = -1; i < n; ++i) {
27+
while(j >= 0 && pattern[j + 1] != pattern[i])
28+
j = failure[j];
29+
if(pattern[j + 1] == pattern[i])
30+
++j;
31+
failure[i] = j;
32+
}
33+
34+
for(int i = 0, j = -1; i < m; ++i) {
35+
while(j >= 0 && pattern[j + 1] != target[i])
36+
j = failure[j];
37+
if(pattern[j + 1] == target[i])
38+
++j;
39+
if(j == n - 1) {
40+
return i - j;
41+
}
42+
}
43+
44+
return -1;
45+
}
46+
};

0 commit comments

Comments
 (0)