leetcode 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.)
class Solution(object): def repeatedSubstringPattern(self, s): """ :type s: str :rtype: bool """ #return True if re.match(r"(\w+)*", s) else False def is_repeat(s1, s2): return s1 == s2*(len(s1)/len(s2)) l = len(s) for i in xrange(1, l/2+1): if l % i == 0: if is_repeat(s, s[:i]): return True return False
上面是暴力解法,下面是技巧解法:
class Solution(object): def repeatedSubstringPattern(self, s): """ :type s: str :rtype: bool """ #return True if re.match(r"(\w+)*", s) else False if not s: return False ss = (s + s)[1:-1] return ss.find(s) != -1
解释:
Let's say T = S + S
.
"S is Repeated => From T[1:-1] we can find S
" is obvious.
If from T[1:-1]
we found S
at index p-1
, which is index p
in T
and S
.
let s1 = S[:p]
, S
can be represented as s1s2...sn
, where si
stands for substring rather than character.
then we know T[p:len(S) + p] = s2s3...sn-1sns1 = S = s1s2...sn-2sn-1sn
.
So s1 = s2, s2 = s3, ..., sn-1 = sn, sn = s1
,Which means S is Repeated.
其实你自己画图下就知道了!!!假设:
s=s1s2s3s4
T=s1s2s3s4s1s2s3s4
去掉收尾,则有:T'=s2s3s4s1s2s3,如果在这里面找到了s1s2s3s4,假设找到的为0位置则:
s2s3s4s1=s1s2s3s4,说明:s2==s1,s3==s2,s4==s3,s1==s4,不就是单个字符重复了嘛!同样,假设出现的位置为1,也可以类似推导!