kirqe
kirqe

Reputation: 2470

Find the longest substring in a string

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

Upvotes: 2

Views: 1495

Answers (3)

kirqe
kirqe

Reputation: 2470

Here's another solution. It's bigger but it still works)

def most_friquent_char_in_a_row(my_str)
  my_str = my_str.chars
  temp=[]
  ary=[]

  for i in 0..my_str.count-1
    if my_str[i]==my_str[i+1]
      temp<<my_str[i] unless temp.include?(my_str[i])
      temp<<my_str[i+1]   
    else 
      ary<<temp
      temp=[]
    end
  end
  result = ary.max_by(&:size).join
  p "#{result} - #{result.size}" 
end

Upvotes: 0

BroiSatse
BroiSatse

Reputation: 44685

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)

Upvotes: 8

tadman
tadman

Reputation: 211570

Here's a solution using a regular expression:

LETTER_MATCH = Regexp.new(('a'..'z').collect do |letter|
  "#{letter}+"
end.join('|'))

def repeated(string)
  string.scan(LETTER_MATCH).sort_by(&:length).last
end

Upvotes: 2

Related Questions