Created
September 15, 2015 16:09
-
-
Save stevenkaras/fe6749012ff2d40168a8 to your computer and use it in GitHub Desktop.
Manacher's Algorithm for finding palindromic sequences in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Detect all the palindromic sequences in a given string | |
# | |
# @return [<Range>] a list of all the palindromes in the given string | |
def all_palindromes(string) | |
preprocessed = "^#{string.chars.join("#")}$" | |
palindromes = [0] * preprocessed.length | |
center = 0 | |
right = 0 | |
for i in 1...preprocessed.length | |
mirror = center * 2 - i | |
palindromes[i] = (right > i) ? [right-i, palindromes[mirror]].min : 0 | |
while preprocessed[i + 1 + palindromes[i]] == preprocessed[i - 1 - palindromes[i]] | |
palindromes[i] += 1 | |
end | |
if i + palindromes[i] > right | |
center = i | |
right = i + palindromes[i] | |
end | |
end | |
result = [] | |
palindromes.each_with_index do |length, center| | |
start = center - length | |
stop = center + length | |
start = start / 2 | |
stop = (stop - 1) / 2 | |
next unless start < stop | |
result << (start..stop) | |
end | |
return result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment