代码随想录算法训练营day9 | 28. 实现 strStr()、459.重复的子字符串

28. 实现 strStr()

暴力解法:双重循环,外层是haystack字符串,内层是needle字符串

KMP算法:当haystack字符串和needle字符串已经匹配部分之后,如果下一个不匹配后,暴力法将会从头开始匹配,已经匹配的部分不能被充分利用

KMP算法能够充分利用已经匹配的部分,首先对needle求最长公共前后缀next,因为对已经匹配上的部分得到最长公共前后缀后可以确定移动位置;然后循环haystack字符串,与needle进行匹配,利用求得的next得到needle下一个匹配的位置

如何求最长公共前后缀
  1. 初始化
  2. 处理前后缀不相同的情况
  3. 处理前后缀相同的情况

使用 前缀表统一减一的方式

初始化
int j = -1;
next[0] = j;

定义两个指针i和j,j指向前缀末尾位置,i指向后缀末尾位置。

next[i] 表示 i(包括i)之前最长相等的前后缀长度(其实就是j)

处理前后缀情况

需要注意:前后缀不相同的情况一定要放在相同的前面,不然有时就会漏处理第一个字符的情况,因为回退到j==-1后需要比较s[i]和s[j + 1]的情况才能确定第一个字符的情况

void getNext(int* next, const string& s){
    int j = -1;
    next[0] = j;
    for(int i = 1; i < s.size(); i++) { // 注意i从1开始
        while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同了
            j = next[j]; // 向前回退
        }
        if (s[i] == s[j + 1]) { // 找到相同的前后缀
            j++;
        }
        next[i] = j; // 将j(前缀的长度)赋给next[i]
    }
}
字符串与模式串进行匹配

求完最长公共前后缀之后就可以循环haystack字符串,与needle进行匹配

int j = -1; // 因为next数组里记录的起始位置为-1
for (int i = 0; i < s.size(); i++) { // 注意i就从0开始
    while(j >= 0 && s[i] != t[j + 1]) { // 不匹配
        j = next[j]; // j 寻找之前匹配的位置
    }
    if (s[i] == t[j + 1]) { // 匹配,j和i同时向后移动
        j++; // i的增加在for循环里
    }
    if (j == (t.size() - 1) ) { // 文本串s里出现了模式串t
        return (i - t.size() + 1);
    }
}
前缀表统一减一的方式
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        next = [-1] * len(needle)
        self.getNext(needle, next)
        j = -1
        for i in range(len(haystack)):
            while haystack[i] != needle[j + 1] and j >= 0:
                j = next[j]
            if haystack[i] == needle[j + 1]:
                j += 1
            if j == len(needle) - 1:
                return i - j
        return -1

    def getNext(self, s, next):
        j = -1
        next[0] = j
        for i in range(1, len(s)):
            while s[j + 1] != s[i] and j >= 0:
                j = next[j]
            if s[j + 1] == s[i]:
                j += 1
            next[i] = j
前缀表不减一的方式
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        next = [0] * len(needle)
        self.getNext(needle, next)
        j = 0
        for i in range(len(haystack)):
            while haystack[i] != needle[j] and j > 0:
                j = next[j-1]
            if haystack[i] == needle[j]:
                j += 1
            if j == len(needle):
                return i - j + 1
        return -1

    def getNext(self, s, next):
        j = 0
        next[0] = j
        for i in range(1, len(s)):
            while s[j] != s[i] and j > 0:
                j = next[j-1]
            if s[j] == s[i]:
                j += 1
            next[i] = j

注:两种思想是一样的,只是实现有点差别

459.重复的子字符串

两个字符串拼接,去除首尾元素,如果包含原字符串则说明是重复的子字符串

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        # 使用find, s+s,去除第一位和最后一位,还能找到s说明有重复子串
        if len(s) <= 1:
            return False
        ss = s[1:] + s[:-1]
        return ss.find(s) != -1

使用KMP算法,推理过程比较复杂,主要在于 next[-1] != -1 and len(s) % (len(s) - (next[-1]+1)) == 0 这一步的判断

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        if len(s) <= 1:
            return False
        # 得到next数组
        next = [-1] * len(s)
        self.getNext(s, next)
        if next[-1] != -1 and len(s) % (len(s) - (next[-1]+1)) == 0:
            return True
        return False

    def getNext(self, s, next):
        j = -1
        next[0] = j
        for i in range(1, len(s)):
            while s[i] != s[j+1] and j >= 0:
                j = next[j]
            if s[i] == s[j+1]:
                j += 1
            next[i] = j

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值