我的目标是找到给定字符串中重复字母最多的单词。例如,"aabcc ddeeteefef iijjfff"
会回来"ddeeteefef"
因为"e"
在这个单词中重复了五次,这比所有其他重复字符都多。
到目前为止,这是我得到的,但它有很多问题并且不完整:
def LetterCountI(str)
s = str.split(" ")
i = 0
result = []
t = s[i].scan(/((.)\2+)/).map(&:max)
u = t.max { |a, b| a.length <=> b.length }
return u.split(//).count
end
我的代码只能找到连续的模式;如果模式被中断(例如"aabaaa"
,它计算三次而不是五次)。
str.scan(/\w+/).max_by{ |w| w.chars.group_by(&:to_s).values.map(&:size).max }
-
scan(/\w+/)
— 创建所有“单词”字符序列的数组
-
max_by{ … }
— 找到该块内给出最大值的单词
-
chars
— 将字符串拆分为字符
-
group_by(&:to_s)
— 创建一个哈希,将每个字符映射到所有出现的字符的数组
-
values
— 只需获取所有出现的数组
-
map(&:size)
— 将每个数组转换为该数组中的字符数
-
max
— 找到最大的字符并将其用作结果max_by
检查
Edit: 写得不太紧凑:
str.scan(/\w+/).max_by do |word|
word.chars
.group_by{ |char| char }
.map{ |char,array| array.size }
.max
end
编写的功能较少,并且使用较少的 Ruby 主义(使其看起来更像“其他”语言):
words_by_most_repeated = []
str.split(" ").each do |word|
count_by_char = {} # hash mapping character to count of occurrences
word.chars.each do |char|
count_by_char[ char ] = 0 unless count_by_char[ char ]
count_by_char[ char ] += 1
end
maximum_count = 0
count_by_char.each do |char,count|
if count > maximum_count then
maximum_count = count
end
end
words_by_most_repeated[ maximum_count ] = word
end
most_repeated = words_by_most_repeated.last
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)