博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 459. Repeated Substring Pattern
阅读量:6697 次
发布时间:2019-06-25

本文共 1859 字,大约阅读时间需要 6 分钟。

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: TrueExplanation: It's the substring "ab" twice.

Example 2:

Input: "aba"Output: False

Example 3:

Input: "abcabcabcabc"Output: TrueExplanation: 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,也可以类似推导!

 

转载地址:http://awmoo.baihongyu.com/

你可能感兴趣的文章
[20150629]12c物化视图刷新Out of place
查看>>
基于.net开发chrome核心浏览器【四】
查看>>
Linux下编译安装Apache httpd 2.4
查看>>
.subversion
查看>>
TensorFlow训练单特征和多特征的线性回归
查看>>
linux的du使用方法
查看>>
STL容器删除元素的陷阱
查看>>
分析数据库CitusDB:提供弹性计算能力
查看>>
国产毫米波雷达领域的领头羊,木牛科技将在明年量产77GHz汽车雷达
查看>>
IOS7.1.1真的像网上流传的那么好?没有任何问题么??
查看>>
WiFi密码分享有妙招 不必口头相传
查看>>
剖析Docker Swarm和Mesos:是什么?如何结合?有什么优势?
查看>>
李飞飞:为什么计算机视觉对机器人如此重要?
查看>>
Unity AI副总裁Danny Lange:如何用AI助推游戏行业?
查看>>
《Effective Objective-C 2.0》1、熟悉Objective-C
查看>>
用 Flask 来写个轻博客 (1) — 创建项目
查看>>
OpenSceneGraph in ActiveX by ActiveQt
查看>>
南海发展大数据产业 建设新型智慧城市
查看>>
安卓APP破解利器之FRIDA
查看>>
数据中心传输需求成以太网市场巨大推动力
查看>>