459. Repeated Substring Pattern

题意:Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: “abab”

Output: True

Explanation: It’s the substring “ab” twice.

Example 2:

Input: “aba”

Output: False

Example 3:

Input: “abcabcabcabc”

Output: True

Explanation: It’s the substring “abc” four times. (And the substring “abcabc” twice.)

思路:这题用两次循环一次去找使可以找到答案的,但是时间复杂度太高,所以其中一种方法是可以用KMP算法来做,只要求出next数组,next数组中包含了重复子字符串的信息即可,但是这又有个问题了,next数组的求取方法有很多种,但是对这题来说,太细化的next数组对这题是不适合的,具体可以看这篇博客KMP多种模式数组的比较(Python版代码),比如对于文中细化第二种的next数组求法(第一种更不适合,因为完全没有规律),T=’abad’和’abab’,对应的next数组都是’[-1,0,-1,1]’,而对于不细化的next数组求法,对应的next数组为’[-1,-1,0,-1]’和’[-1,-1,0,1]’,前一种对应的求next数组方法如下:

def getPrefix(needle):
    i, j, n = -1, 0, len(needle)
    next = [-1] * n
    while j < n - 1:
        if i == -1 or needle[i] == needle[j]:
            i, j = i + 1, j + 1
            next[j] = i
        else:
            i = next[i]
    return next

后一种对应的方法为:

def getPrefix1(self, pattern):
    prefix = [-1] * len(pattern)
    j = -1
    for i in xrange(1, len(pattern)):
        while j > -1 and pattern[j + 1] != pattern[i]:
            j = prefix[j]
        if pattern[j + 1] == pattern[i]:
            j += 1
        prefix[i] = j
    return prefix

利用后一种求next数组的方法,再加上以下代码就可以验证是否为重复字串:

prefix = getPrefix(str)
return prefix[-1] != -1 and (prefix[-1] + 1) % (len(str) - prefix[-1] - 1) == 0

当然,下面还有一种比较奇特的方法,因为对于串S重复子串至少重复一次,所以把该串第一个字符去掉构成S1,再把该串的最后一个字符去掉构成S2,则S1+S2构成的串肯定含有S,即:

def repeatedSubstringPattern(self, str):

        """
        :type str: str
        :rtype: bool
        """
        if not str:
            return False

        ss = (str + str)[1:-1]
        return ss.find(str) != -1

可以写成:

def repeatedSubstringPattern(self, str):
    return str in (2 * str)[1:-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值