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.)

分析:
这道题是判断一个字符串是不是某个字符串重复若干次的问题

思路:
写在这里就是想秀一下我的一行代码,嗨呀,是真滴骚!

1
2
3
4
5
6
def repeatSubstringPattern(s):
return any(s[:i]*(len(s)//i)==s for i in range(1,len(s)) if s[i] == s[0])

107 / 107 test cases passed.
difficulty: easy
Runtime: 330 ms

感叹:我还是急了,这道题要是仔细想一下肯定不会这样的,这个解法还是有点东西的,用反证法很容易证

1
2
def repeatSubstringPattern(s):
return s in (s+s)[1:-1]