459. Repeated Substring Pattern

来源:互联网 发布:caffe bn不收敛 编辑:程序博客网 时间:2024/05/16 15:04

题意: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