Created
September 22, 2018 05:03
-
-
Save woodRock/e2dc693a7de795d97e3204d3b0d8b2ce to your computer and use it in GitHub Desktop.
Palindromes
This file contains 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
def all_palindromes(word) | |
q = "@#" | |
q += word.chars.join("#") | |
q += "\#$" | |
puts q | |
pld = [0] * q.size() | |
c,r = 0,0 | |
search = (1...q.size()) | |
search.each do |i| | |
mirror = c - (i - c) | |
if r > i | |
pld[i] = [r - 1, pld[mirror]].min | |
end | |
while q[i+1+pld[i]] == q[i-1-pld[i]] | |
pld[i] += 1 | |
end | |
if i+pld[i] > r | |
c = i | |
r = i + pld[i] | |
end | |
end | |
max_pld,ctr_idx = 0,0 | |
search.each do |i| | |
if pld[i] > max_pld | |
max_pld = pld[i] | |
ctr_idx = i | |
end | |
end | |
puts max_pld | |
return word[(ctr_idx - 1 - max_pld)/2, max_pld] | |
end | |
word = "banana" | |
puts all_palindromes(word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment