2024/12/17 【字符串】LeetCode 459.重复的子字符串🌺🌺🌺 【❌】字符串篇总结
https://programmercarl.com/0459.%E9%87%8D%E5%A4%8D%E7%9A%84%E5%AD%90%E5%AD%97%E7%AC%A6%E4%B8%B2.html#%E6%80%9D%E8%B7%AF
https://leetcode.cn/problems/repeated-substring-pattern/
https://programmercarl.com/%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%80%BB%E7%BB%93.html#%E4%BB%80%E4%B9%88%E6%98%AF%E5%AD%97%E7%AC%A6%E4%B8%B2
子串结束位置大于中间位置的话,一定不能重复组成字符串。
如果 next[len - 1] != -1,则说明字符串有最长相同的前后缀(就是字符串里的前缀子串和后缀子串相同的最长长度,这里的next数组是以统一减一的方式计算的)
解法一:KMP算法的next数组(不减一)
具体的分析过程见链接2
class Solution: def getNext(self, next, s): j = 0 for i in range(1, len(s)): while j > 0 and s[i] != s[j]: j = next[j-1] if s[i] == s[j]: j += 1 next[i] = j def repeatedSubstringPattern(self, s: str) -> bool: n = len(s) next = [0]*n self.getNext(next, s) if next[n-1] != 0 and n % (n-next[n-1]) == 0: return True return False
解法2:KMP,next数组,减一
解法3:移动匹配(方法思路见代码随想录)使用find函数
class Solution: def repeatedSubstringPattern(self, s: str) -> bool: ss = s[1:]+s[:-1] print(ss) return ss.find(s) != -1
解法4:暴力法
class Solution: def repeatedSubstringPattern(self, s: str) -> bool: substr = "" n = len(s) for i in range(1, n//2+1): if n % i == 0: substr = s[:i] if substr*(n//i) == s: return True return False
字符串:总结篇
1.双指针法:很多数组填充类的问题,都可以先预先给数组扩容带填充后的大小,然后在从后向前进行操作。
2.反转系列:当需要固定规律一段一段去处理字符串的时候,要想想在在for循环的表达式上做做文章。
3.KMP