gpt4 book ai didi

ruby - ruby 中的数据结构只存储唯一元素?

转载 作者:太空宇宙 更新时间:2023-11-03 17:26:22 25 4
gpt4 key购买 nike

我想要一个 Ruby 中的数据结构,它只存储一次字符串并在我下次尝试将其放入时拒绝它(类似于“SET”)。实现必须是最有效的(例如,优于数组中的线性搜索)。

我也尝试过为此目的使用哈希,但是具有相同值的多个字符串(这些字符串是我从一些现有字符串的切片操作中获得的)进入哈希,似乎正在计算它们的不同哈希值。

最好和最有效的出路是什么?我不想使用 ruby gem 。我正在研究在线评委提供的拼图解决方案,为此我只能提交自己的代码。

这是我写的代码片段:

for string in @string_store do
for c in 0...string.length
index_to_sum=0
while c+index_to_sum<string.length do
substring=string[c..(c+index_to_sum)]
unless @hash_store[substring]=='X'
@hash_store[substring]='X'
end
index_to_sum+=1
end
end
end

最佳答案

Ruby Set怎么样? :)

require 'set'
s1 = Set.new [1, 2] # -> #<Set: {1, 2}>
s2 = [1, 2].to_set # -> #<Set: {1, 2}>
s1 == s2 # -> true
s1.add("foo") # -> #<Set: {1, 2, "foo"}>
s1.merge([2, 6]) # -> #<Set: {6, 1, 2, "foo"}>
s1.subset? s2 # -> false
s2.subset? s1 # -> true

虽然它使用了require,但 Ruby Set 是 Ruby 标准库的一部分,所以它应该完全可以被您的代码提交接受

关于ruby - ruby 中的数据结构只存储唯一元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8745193/

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