["b", "a"] "b" 在 "a"-6ren">
gpt4 book ai didi

arrays - 按重复顺序排列的项目

转载 作者:数据小太阳 更新时间:2023-10-29 07:42:25 24 4
gpt4 key购买 nike

我希望方法 repeated 获取一个字符串,并按照重复的顺序返回其重复字符的数组。区分大小写适用。在这个例子中,

repeated("abba") # => ["b", "a"]

"b""a" 之前重复。另一个例子:

repeated("limbojackassin the garden") # => ["a", "s", "i", " ", "e", "n"]

像这样工作:

limbojackassin the garden 
|--^ "a"
|^ "s"
|----------^ "i"
|---^ " "
* "a" ignored
|-----^ "e"
|----------^ "n"

我有这个方法。

def repeated(str)
puts str.chars.select{|i| str.count(i) > 1}.uniq
end

意外地工作:

repeated("limbojackassin the garden")
# => ["i", "a", "s", "n", " ", "e"]
# => expected ["a", "s", "i", " ", "e", "n"]
repeated("Pippi")
# => ["i", "p"]
# => expected ["p", "i"]
repeated("apple")
# => as expected ["p"]

如何检查数组项索引之间的距离?

最佳答案

def repeated(str)
puts(str.each_char.with_object([{}, []]) do
|c, (h, a)| h[c] ? a.push(c) : h.store(c, true)
end.last.uniq)
end

关于arrays - 按重复顺序排列的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34181231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com