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,也可以类似推导!

  • 相关阅读:
    清北学堂2019NOIP提高储备营DAY1
    最小生成树--克鲁斯卡尔算法(Kruskal)
    关于队列(还有广度优先搜索的例题)
    染色问题
    行列式的相关知识
    素数筛法
    中国剩余定理(孙子定理)
    AOJ 9.University
    AOJ 8.童年生活二三事
    AOJ 7.Redraiment猜想
  • 原文地址:https://www.cnblogs.com/bonelee/p/9153275.html
Copyright © 2011-2022 走看看