题目地址:
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/
给定两个字符串 s s s和 p p p,要求在 s s s中找到 p p p的第一次出现,然后将其删去,接着继续找,再删去,直到找不到 p p p为止。返回最终的结果。
字符串匹配可以用KMP算法,由于 p p p始终不变,可以先算一下 p p p的next数组,然后每次从 s s s中找 p p p的第一次出现,删去之,再重复进行这个过程。代码如下:
public class Solution {
public String removeOccurrences(String s, String part) {
int[] ne = buildNext(part);
int pos = -1;
while ((pos = kmp(s, part, ne)) != -1) {
s = s.substring(0, pos) + s.substring(pos + part.length());
}
return s;
}
private int kmp(String s, String p, int[] ne) {
for (int i = 0, j = 0; i < s.length(); ) {
if (j == -1 || s.charAt(i) == p.charAt(j)) {
i++;
j++;
} else {
j = ne[j];
}
if (j == p.length()) {
return i - j;
}
}
return -1;
}
private int[] buildNext(String p) {
int[] ne = new int[p.length()];
for (int i = 0, j = ne[0] = -1; i < p.length() - 1; ) {
if (j == -1 || p.charAt(i) == p.charAt(j)) {
i++;
j++;
ne[i] = p.charAt(i) != p.charAt(j) ? j : ne[j];
} else {
j = ne[j];
}
}
return ne;
}
}
时间复杂度 O ( l s 2 l p ) O(\frac{l_s^2}{l_p}) O(lpls2),空间 O ( l p ) O(l_p) O(lp)。