【Leetcode】1910. Remove All Occurrences of a Substring

题目地址:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值