Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the longest substring in a string

Tags:

ruby

I would like to find the longest sequence of repeated characters in a string.

ex:

"aabbccc" #=> ccc
"aabbbddccdddd" #=> dddd

etc

In the first example, ccc is the longest sequence because c is repeated 3 times. In the second example, dddd is the longest sequence because d is repeated 4 times.

It should be something like this:

b = []
a.scan(/(.)(.)(.)/) do |x,y,z|
    b<<x<<y<<z if x==y && y==z
end

but with some flags to keep the count of repeating, I guess

like image 1000
kirqe Avatar asked Mar 17 '26 18:03

kirqe


1 Answers

This should work:

string = 'aabbccc'
string.chars.chunk {|a| a}.max_by {|_, ary| ary.length}.last.join

Update:

Explanation of |_, ary|: at this point we have array of 2-element arrays. We only need to use the second one and we ignore the first one. If instead we do |char, ary| some IDEs would complain about unused local variable. Placing _ tells ruby to ignore that value.

Using regex:

We can achieve same thing with regex:

string.scan(/([a-z])(\1*)/).map(&:join).max_by(&:length)
like image 119
BroiSatse Avatar answered Mar 22 '26 22:03

BroiSatse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!