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.)
Python Solution 1:
class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
return s in s[1:] + s[:-1]
Python Solution 2:
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 3: return max(nums)
origin_max = _max = max(nums)
for _ in range(2):
tmp = None
for num in nums:
if num < _max:
if tmp is None:
tmp = num
else:
tmp = max(tmp, num)
if tmp is None: return origin_max
_max = tmp
return _max
Summary:
- https://discuss.leetcode.com/topic/68206/easy-python-solution-with-explaination/6
- The basic idea is:
s in s[1:] + s[:-1]provess == s1s2 == s2s1, iflen(s1) == len(s2), problem solved.- WLOG, let's say
len(s1) < len(s2). s1s2 == s2s1meanss2 == s1s3 == s3s1. iflen(s1) == len(s3), problem solved.- Otherwise,
s1has to be shorter thans2.- The reason is that
scan be represented ass1"s3s1s1"s3s1ands3"s1s1s3"s1s1. - If
s3is shorter thans1, in the first step,scould be equal tos3s4 == s4s3, so it's false.
- The reason is that
s1s3 == s3s1meanss3 == s1s4 == s4s1.- ...
s == s1s1s1s1...s1sn == sns1...s1s1s1, untillen(sn) == len(s1), problem solved.
LeetCode: 459. Repeated Substring Pattern





近期评论