Problem Statement
(Source) 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.)
Solution
class Solution(object):
def repeatedSubstringPattern(self, str):
"""
:type str: str
:rtype: bool
"""
n = len(str)
for i in xrange(1, n):
if n % i == 0 and self.check(str, i):
return True
return False
def check(self, s, x):
return all(s[i] == s[i%x] for i in xrange(len(s)))
To make it more concise:
class Solution(object):
def repeatedSubstringPattern(self, str):
"""
:type str: str
:rtype: bool
"""
return any(len(str) % i == 0 and self.check(str, i) for i in xrange(1, len(str)))
def check(self, s, x):
return all(s[i] == s[i%x] for i in xrange(len(s)))
It can even be written in one-line, but rather ugly :)