Leetcode 2950. 可整除子串的数量
每个英文字母都被映射到一个数字,如下所示。
image.png
如果字符串的字符的映射值的总和可以被字符串的长度整除,则该字符串是 可整除 的。
给定一个字符串 s,请返回 s 的 可整除子串 的数量。
子串 是字符串内的一个连续的非空字符序列。
示例 1:
输入:word = "asdf"
输出:6
解释:上表包含了有关 word 中每个子串的详细信息,我们可以看到其中有 6 个是可整除的。
示例 2:
输入:word = "bdh"
输出:4
解释:4 个可整除的子串是:"b","d","h","bdh"。
可以证明 word 中没有其他可整除的子串。
示例 3:
输入:word = "abcd"
输出:6
解释:6 个可整除的子串是:"a","b","c","d","ab","cd"。
可以证明 word 中没有其他可整除的子串。
提示:
1 <= word.length <= 2000
word 仅包含小写英文字母。
废话不多说,直接上代码
# @param {String} word
# @return {Integer}
def count_divisible_substrings(word)
m = ("a".ord.."z".ord).to_a
h = {}
m.each_with_index do |m,i|
case i
when 0,1 then h[m.chr] = 1
when 2,3,4 then h[m.chr] = 2
when 5,6,7 then h[m.chr] = 3
when 8,9,10 then h[m.chr] = 4
when 11,12,13 then h[m.chr] = 5
when 14,15,16 then h[m.chr] = 6
when 17,18,19 then h[m.chr] = 7
when 20,21,22 then h[m.chr] = 8
when 23,24,25 then h[m.chr] = 9
end
end
word = word.chars.map {|it| h[it]}
x = [word[0]]
for i in 1...word.length
x << x[-1] + word[i]
end
cnt = word.length
word.each_with_index do |w,i|
if i > 0
if x[i] % (i+1) == 0
cnt += 1
end
for j in 0...word.length - (i+1)
if (x[i+j+1] - x[j])%(i+1) == 0
cnt += 1
end
end
end
end
cnt
end