iT邦幫忙

2023 iThome 鐵人賽

DAY 5
0
自我挑戰組

Leetcode Top Interview 150系列 第 5

459. Repeated Substring Pattern

  • 分享至 

  • xImage
  •  

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

上一篇
2. Add Two Numbers
下一篇
189. Rotate Array
系列文
Leetcode Top Interview 15015
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
jrnalts
iT邦新手 5 級 ‧ 2023-09-14 11:50:24

網路上查到的神級解法

(s+s)[1..-2].include? s

我要留言

立即登入留言