Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.
Example 2:Input: s = "aba"
Output: false
Example 3:Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times or the substring "abcabc" twice.Constraints:
1 <= s.length <= 104
s consists of lowercase English letters.
# @param {String} s
# @return {Boolean}
def repeated_substring_pattern(s)
return false if s.length == 1
n = 1 # 重複單位
s.split('').each_with_index do |ch, idx|
next if idx == 0
times = s.length / n
s[0..(idx-1)] * times == s ? break : n += 1
end
return false if s.length % n != 0 # 無法除以重複單位
return false if n > (s.length / 2) # 都超過一半了肯定不行
true
end