longest_substring
is a library extension to String that finds the longest sequence of same chars inside an array (substring).
It has methods to return the substring and its initial and final positions.
Run bundle install
first.
require_relative "lib/longest_substring"
- String#longest_substring
# returns largest substring of same chars
"Pressaaao".longest_substring
=> "aaa"
- String#longest_substring_positions
# returns positions of largest substring
"Pressaaao".longest_substring_positions
=> [5,9]
- Simpler version: HEAD
- Optimized and compact version: optimizations branch
Take Loop
as an example string.
- String is transformed in array
"Loop" => [ "L", "o", "o", "p" ]
- Adjacent substrings of same char are generated
[ ["L"], ["o", "o"], ["p"] ]
- Next we select the largest one
[ … ["o", "o"] … ]
- Finally we find the positions of the substring in the original string
substring = "oo"
positions = [1,3]