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.

给定非空字符串检查是否可以通过获取它的子字符串并将子字符串的多个副本附加在一起来构造它。 您可以假设给定的字符串仅由小写英文字母组成,其长度不超过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.)

python实战:

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

class Solution(object):
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        # 1. 定义一个空列表存放字符串数组
        l_s = []
        for c in s:
            l_s.append(c)
        l_s_set = set(l_s)
        if len(l_s_set) == 1:
            print("True")
            return True
        len_s = len(l_s)
        if len_s % 2 == 0:
            mid = int(len_s / 2)
            for i in range(0, mid):
                if l_s[i] == l_s[mid+i]:
                    continue
                else:
                    print("False")
                    return False
                    break
            if i == mid:
                print("True")
                return True

    def repeatedSubstringPattern2(self, str):

        """
        :type str: str
        :rtype: bool
        """
        if not str:
            return False

        ss = (str + str)[1:-1]
        s2 = str + str
        print(s2)
        print(ss)
        return ss.find(str) != -1

if __name__ == '__main__':
    s = "aaabaa"
    Solution().repeatedSubstringPattern2(s)

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦