public
Last active

Find the Maximum Length Palindrome in a String Provide a method that takes a string and returns the maximum length palindrome. A palindrome is a word, phrase or number that can be read the same in either direction.

  • Download Gist
max_palindrome.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
def max_palindrome(str)
i,size = 0,str.length
until palindrome?(str,i,size) do
if i < str.length-size then i=i+1 else i=0; size=size-1 end
end
size
end
 
def palindrome?(str,i,size)
(i..i+size/2-1).each{ |j| if str[j] != str[2*i+size-j-1] then return false end }
true
end
 
puts "Max Palindrome: #{max_palindrome("abcba")}"
puts "Max Palindrome: #{max_palindrome("aabcbdb")}"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.