天天看点

【Leetcode_总结】 459. 重复的子字符串 - python

Q:

给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。

示例 1:

输入: "abab"

输出: True

解释: 可由子字符串 "ab" 重复两次构成。
      

示例 2:

输入: "aba"

输出: False      

思路1:使用KMP算法,返回的条件是 p 为next [-1] p > 0 and size % (size - p) 代码如下:

class Solution:
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        size = len(s)
        next = [0] * size
        for i in range(1, size):
            k = next[i - 1]
            while s[i] != s[k] and k:
                k = next[k - 1]
            if s[i] == s[k]:
                next[i] = k + 1
        p = next[-1]
        return p > 0 and size % (size - p) == 0
           
【Leetcode_总结】 459. 重复的子字符串 - python

思路2:

如果字符串重复的,那么同一个字符串相加之后,内部必然会有重复,如abab 相加后为 abababab 字符串存在于[-1:1]区间内

如果是本身不是重复的字符串 如aba 那么相加后为abaaba 在区间[-1:1]内不存在原子串,代码如下:

class Solution:
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        return s in (s*2)[1:-1]
           
【Leetcode_总结】 459. 重复的子字符串 - python