[InterviewBit] Implement StrStr

Implement StrStr

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
vector<int> PI(string p) {
vector<int> pi(p.length());
for(int i = 1, j = 0; i < p.length(); i++) {
while(j and p[i] != p[j]) j = pi[j-1];
if(p[i] == p[j]) pi[i] = ++j;
}
return pi;
}

int kmp(string s, string p) {
vector<int> pi = PI(p);
for(int i = 0, j = 0; i < s.length(); i++) {
while(j and s[i] != p[j]) j = pi[j-1];
if(s[i] == p[j]) {
if(++j == p.length()) return i - p.length() + 1;
}
}
return -1;
}

int Solution::strStr(const string A, const string B) {
return kmp(A,B);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/27/PS/interviewbit/implement-strstr/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.