栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

leetcode 1910. Remove All Occurrences of a Substring [Python]

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode 1910. Remove All Occurrences of a Substring [Python]

题目做法有点儿扯,每次找到一个和part相同的子串就要删除,然后在新的string基础上继续比对。KMP值返回第一个找到重复part的位置。

class Solution:
    def removeOccurrences(self, s: str, part: str) -> str:
        if part not in s:return s
        res = self.kmp(part, s)
        #print(res)
        s = list(s)
        #print(s)
        index = res
        for i in range(len(part)):
            s[index + i] = ' '
        newstr = ''
        for char in s:
            if char != ' ':
                newstr += char
        #print(newstr)
        return self.removeOccurrences(newstr, part)
        
    def kmp(self, p, s):
        m = len(p)
        p = ' ' + p
        n = len(s)
        s = ' ' + s
        ne = [0]*100010
        j =0
        res = -1
        for i in range(2, m+1):
            while j and p[i] != p[j+1]:
                j = ne[j]
            if p[i] == p[j+1]:
                j += 1
            ne[i] = j
        j = 0
        for i in range(1, n+1):
            while j and s[i] != p[j+1]:
                j = ne[j]
            if s[i] == p[j+1]:
                j += 1
            if j == m:
                return i-j
                j = ne[j]  
        return res  
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/675041.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号