我正在学习 Ruby。作为我的 HW 的一部分,我要在字符串的一行中找到第一次出现的两个重复字符,并返回重复的字符。这是我想出的:
require 'set'
def find_a_dup_using_set(arr)
s = Set.new
arr.find { |e| !s.add?(e) }
end
p find_a_dup_using_set(["q", "q", "c", "d", "e"])
问题:这是最好的方法吗?也许是因为我还在学习,但我觉得这不是他们想要的,但这是我根据我所做的研究知道什么是有效的。有没有理由不为这样的事情使用数组?
最佳答案
为什么不使用简单的正则表达式呢?
str = 'abccdd'
str[/(.)\1/][0]
=> 'c'
此处的正则表达式对每个字符进行分组并找到第一个连续的对。然后我们通过调用 0 索引来获取第一个字符。
在 ruby 中有几种使用 Regular Expression 的方法在一个字符串上。所以你可以把它放在一个方法中。
def find_first_dup_in_string(str)
str[/(.)\1/][0]
end
这是 tadman 答案的一个变体,我将包括基准来比较 UPDATED 以根据评论使用 each_char
。
def find_first_dup_a(str)
d = ''
str.each_char.each_cons(2){|c| d = c[0]; break if c[0] == c[1] }
d
end
alpha=[*'a'..'z']
str = ''
1000.times{ str << alpha.sample}
cycles = 100000
Benchmark.bm do |x|
x.report(:ruby) { cycles.times { find_first_dup_a(str) } }
x.report(:regex) { cycles.times { find_first_dup_in_string(str) } }
end
ruby 0.330000 0.010000 0.340000 ( 0.338940)
regex 0.140000 0.000000 0.140000 ( 0.151719)
=> [
[0] #<Benchmark::Tms:0x00007fb6a0bd4c88 @label="ruby", @real=0.33893999992869794, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=0.33000000000000007, @total=0.3400000000000001>,
[1] #<Benchmark::Tms:0x00007fb6a2601390 @label="regex", @real=0.1517189999576658, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.14000000000000057, @total=0.14000000000000057>
]
还有一个有趣的巧合,没有任何关系:)
14.0/33.0 * 100
=> 42.42424242424242
关于ruby - 返回字符串中的重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55776843/