[LeetCode] Implement strStr()

28. Implement strStr()

Implement strStr().

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

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

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
class Solution {
vector<int> getPi(string& s) {
vector<int> pi(s.length());
for(int i = 1, j = 0; i < s.length(); i++) {
while(j > 0 and s[i] != s[j])
j = pi[j-1];
if(s[i] == s[j])
pi[i] = ++j;
}
return pi;
}
public:
int strStr(string st, string ne) {
if(ne.length() == 0) return 0;
vector<int> pi = getPi(ne);
for(int i = 0, j = 0; i < st.length(); i++) {
while(j > 0 and st[i] != ne[j])
j = pi[j-1];
if(st[i] == ne[j]) {
j++;
if(j == ne.length())
return i - j + 1;
}
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/implement-strstr/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.