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.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

 上面是暴力解法,下面是技巧解法:

1
2
3
4
5
6
7
8
9
10
11
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,也可以类似推导!

 

posted @   bonelee  阅读(191)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-06-07 suse的安装命令zypper,类似apt
2017-06-07 ES transport client批量导入
2017-06-07 ES transport client使用
2017-06-07 hdfs du命令是算的一份数据
点击右上角即可分享
微信分享提示