[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
37
38
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;
string res = "";
for(int i = 0, j = 0; i < s.length(); i++) {
res.push_back(s[i]);
while(j and res.back() != p[j]) j = pi[j-1];
if(res.back() == p[j]) {
index.push_back(++j);
if(j == p.length()) {
for(int j = 0; j < p.length(); j++) {
res.pop_back();
index.pop_back();
}
j = index.size() ? index.back() : 0;
}
} else index.push_back(j);

}
return res;
}
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.