459.Repeated Substring Pattern

Tags: [implementation]

Link: https://leetcode.com/problems/repeated-substring-pattern/?tab=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.)

Solution:

class Solution(object):
    def repeatedSubstringPattern(self, str):
        """
        :type str: str
        :rtype: bool
        """
        if str is None:
            raise ValueError('the input is invalid')
        if not str:
            return True

        # len = k * sub_len, k should be an integer which should be greater than 0
        str_len = len(str)
        for sub_len in xrange(1, str_len):
            if str_len % sub_len != 0:
                continue

            sub_str = str[:sub_len]
            new_str = sub_str * (str_len / sub_len)
            if new_str == str:
                return True

        return False

Note:

  • Time complexity = O(n^2), n is the number characters of the given string. Don't forget it will cost T = O(n), when we build the new string and do the comparison between the new_str and str.

results matching ""

    No results matching ""