[英]Fastest way to find the number of unique elements in a string
如何以最佳方式在字符串中找到唯一元素?
示例字符串格式是
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
而且這個測試的結果並不完全令人驚訝(0n 1.8.7p352):
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"]
Set.new("34345667543".chars)
我發現這很好:從字符串中的字符創建一個Set(暗示唯一條目)。
這在上面的基准測試中是缺失的,並且是我測試中第二快的1.9.3-p274(最快的是chars.to_a.uniq)。 雖然我們仍然在這里討論微基准測試,但在應用程序中幾乎不太重要:)
只需使用拆分方法:
"12345".split("")
從字符串中取出字符並從中創建一個Set:
irb(main):001:0> require 'set'
irb(main):002:0> Set.new("123444454321".split(''))
=> #<Set: {"1", "2", "3", "4", "5"}>
.split('')
調用只是按字符.split('')
將字符串分解為數組。 我最初使用String#each_char
,但這是1.8.7中的新功能,你沒有提到你正在使用的Ruby版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.