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.)

题目大意:

给定一个非空字符串,判断它是否可以通过自身的子串重复若干次构成。你可以假设字符串只包含小写英文字母,并且长度不会超过10000

这道题给了我们一个字符串,问其是否能拆成n个重复的子串。那么既然能拆分成多个子串,那么每个子串的长度肯定不能大于原字符串长度的一半,那么我们可以从1遍历到原字符串长度的一半,如果当前长度能被总长度整除,说明可以分成若干个子字符串,我们将这些子字符串拼接起来看跟原字符串是否相等。 如果拆完了都不相等,返回false。

class Solution(object):
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        for i in xrange(1, len(s)/2+1):
            if len(s)%i == 0:
                l = len(s)/i
                sub = s[:i]
                if sub*l == s:
                    return True
        return False

Last updated

Was this helpful?