zoukankan      html  css  js  c++  java
  • 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,也可以类似推导!

  • 相关阅读:
    Delphi 与 C/C++ 数据类型对照表
    JAVA中堆和栈的区别
    关于Column '*' not found 解决方案 Hibernate使用SQL查询返回实体类型,即返回某个类,或实体类
    Oracle笔记
    oracle时间运算
    struts2中iterator标签的相关使用
    url传中文,转码
    表格的css,细线表格
    使用struts 2 获取服务器数据 ongl表达式 标签
    struts 2 Commons FileUpload文件上传
  • 原文地址:https://www.cnblogs.com/bonelee/p/9153275.html
Copyright © 2011-2022 走看看