最佳方式是如何在字符串中找到唯一元素?
示例字符串格式为
myString = "34345667543"
o/p
['3','4','3','5'.....]
这是一个有趣的问题,由于返回了许多几乎相似的结果,我进行了简单的基准测试来决定哪种解决方案实际上最好:
require 'rubygems'
require 'benchmark'
require 'set'
puts "Do the test"
Benchmark.bm(40) do |x|
STRING_TEST = "26263636362626218118181111232112233"
x.report("do split and uniq") do
(1..1000000).each { STRING_TEST.split(//).uniq }
end
x.report("do chars to_a uniq") do
(1..1000000).each { STRING_TEST.chars.to_a.uniq }
end
x.report("using Set") do
(1..1000000).each { Set.new(STRING_TEST.split('')).to_a }
end
end
这个测试的结果并不完全令人惊讶(在1.8.7p352上为0n):
user system total real
do split and uniq 27.060000 0.000000 27.060000 ( 27.084629)
do chars to_a uniq 14.440000 0.000000 14.440000 ( 14.452377)
using Set 41.740000 0.000000 41.740000 ( 41.760313)
并且在1.9.2p180版本上:
user system total real
do split and uniq 19.260000 0.000000 19.260000 ( 19.242727)
do chars to_a uniq 8.980000 0.010000 8.990000 ( 8.983891)
using Set 28.220000 0.000000 28.220000 ( 28.186787)
REE(1.8.7)的结果接近于1.9.2:
user system total real
do split and uniq 19.120000 0.000000 19.120000 ( 19.126034)
do chars to_a uniq 14.740000 0.010000 14.750000 ( 14.766540)
using Set 32.770000 0.120000 32.890000 ( 32.921878)
出于好玩,我也试了一下 Rubinius:
user system total real
do split and uniq 26.100000 0.000000 26.100000 ( 26.651468)
do chars to_a uniq 25.680000 0.000000 25.680000 ( 25.780944)
using Set 22.500000 0.000000 22.500000 ( 22.649291)
虽然 split('\\').uniq
的可读性更高,但是 chars.to_a.uniq
的速度几乎是它的两倍。
有趣的是,在Rubinius上,Set
解决方案是最快的,但在1.9.2上远远不及chars.to_a.uniq
。
使用以下简短代码:
myString.split(//).uniq
>> "34345667543".chars.uniq
=> ["3", "4", "5", "6", "7"]
.to_a
,从而得到更简洁的 "34345667543".chars.uniq
。 - stillenatSet.new("34345667543".chars)
只需使用split方法:
"12345".split("")
irb(main):001:0> require 'set'
irb(main):002:0> Set.new("123444454321".split(''))
=> #<Set: {"1", "2", "3", "4", "5"}>
.split('')
调用只是将字符串按字符拆分成数组。我最初使用了 String#each_char
,但那是在1.8.7中新增的功能,而您没有提到您正在使用哪个版本的Ruby。