459. Repeated Substring Pattern

https://leetcode.com/problems/repeated-substring-pattern/#/description

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.)
Sol 1:
 
Try all possible divisors.
 
Let's say input string can be divided into d parts equally. d is small or equal to the square root of n, and then we check if d and len(str)/ d parts  can be pieced together to the input string.
 
 
class Solution(object):
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        
        # brute force, O(n*2) time
        n = len(s)
        d = 1
        while d * d <= n:
            if n % d == 0:
                 for m in {d, n/d}:
                   if m > 1 and m * s[:n/m] == s:
                        return True
            d += 1
        return False
            

Note:

1 We use a variable m to check if d and len(str)/d can be glued together to the input string. 

 
It is a must to make sure len(str)/d is a divider because the while loop only checks the first half of the string.
 
ex1. str = 'abababab'
 
m in { 2, 8/2=4 }
 
When m = 2:
    2 * 'ababab' == str   :)
 
When m = 4:
    4 * ‘ab’ == str   :)
 
 
 
ex2. str = 'aba'
 
m in {1, 3/1=3 }
 
When m = 1:
    1 * 'aba' == str    :)
 
When m = 3:
    3 * 'a'  != str       :(
 
 
 
 
 
That's the reason why len(s)/d should also be checked! Otherwise string like 'aba' will get the wrong answer. 
 
 
 
Sol 2:
 
If we double the string, then if the string should be in somewhere from the second char to the last char of the doubled-string. 
 
 
 
 
class Solution(object):
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        
        
        if not s:
            return False
            
        ss = (s + s)[1:-1]
        return ss.find(s) != -1
            

Note:

1 ss.find(s) returns the beginning index of s in ss. If not found, then return -1. 

 
 
 

Basic idea:

  1. First char of input string is first char of repeated substring
  2. Last char of input string is last char of repeated substring
  3. Let S1 = S + S (where S in input string)
  4. Remove 1 and last char of S1. Let this be S2
  5. If S exists in S2 then return true else false
  6. Let i be index in S2 where S starts then repeated substring length i + 1 and repeated substring S[0: i+1]
 
 
 
原文地址:https://www.cnblogs.com/prmlab/p/7003860.html