2012-01-14 50 views
1

我們如何獲得並排字母的最大數量?用紅寶石計算最大並排字母數量

例如,如果我們並肩最大字母a統計每方:我使用Ruby 1.9.3

"Muhahaha, hello world!!!!! Aaaaaaaa" # => 7 
"fuu" # => 0 
"foobar" # => 1 
"aaa bbb ccc" # => 3 
"aa bb cc aaaaa ff" # => 5 

。根據字符串類,我不認爲已經有一種方法可以做到這一點。也許Regexp類可能更有用。

你認爲有一種性感的方式來做到這一點?感謝任何建議。

回答

5

我的辦法是:

"Muhahaha, hello world!!!!! Aaaaaaaa".scan(/a+/).max.length #=> 7 

,或者說不會有效(但它應該)

"Muhahaha, hello world!!!!! Aaaaaaaa".scan(/a+/).sort.last.length #=> 7 
+0

如果我們要概括?使這與任何信件一起工作? – 2012-01-14 21:33:29

+0

如果您更改正則表達式中的字母,它將適用於任何。 – Hauleth 2012-01-14 21:37:11

+2

@Hauleth我認爲傑里米正在尋找'letter ='a'; 「Muhahaha,helloooo world !!!!! Aaaaaaaa」.scan(/#{letter} + /)。max.length'。 – steenslag 2012-01-14 21:55:15

1
# returns the longest stretch of the same word character 
str = "Muhahaha, hello world!!!!! Aaaaaaaa" 
str.scan(/\w/).to_set.map { |c| str.scan(/#{c}+/).max }.sort_by(&:length).last.length