[LeetCode] Remove All Occurrences of a Substring

1910. Remove All Occurrences of a Substring

Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:

  • Find the leftmost occurrence of the substring part and remove it from s.

Return s after removing all occurrences of part.

A substring is a contiguous sequence of characters in a string.

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
class Solution {
vector<int> getPi(string& s) {
vector<int> pi(s.length(), 0);
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;
}
string kmp(string& s, string &p) {
vector<int> pi = getPi(p);
vector<int> index(s.length());
int d = 0;
for(int i = 0, j = 0; i < s.length(); i++) {
s[i-d] = s[i];
if(s[i] == p[j]) {
index[i-d] = ++j;
if(j == p.length()) {
d += p.length();
j = i >= d ? index[i-d] : 0;
}
} else if(j > 0) {
j = pi[j-1];
--i;
}
}
return s.substr(0,s.length()-d);
}
public:
string removeOccurrences(string s, string part) {
return kmp(s,part);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/remove-all-occurrences-of-a-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.