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/
子串结束位置大于中间位置的话,一定不能重复组成字符串。
如果 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
标签:459,12,return,self,len,next,字符串,def From: https://www.cnblogs.com/spp20/p/18637949