Skip to content

Instantly share code, notes, and snippets.

@ianmcnally
Created June 30, 2014 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianmcnally/fc0d65c3d461b6458c7b to your computer and use it in GitHub Desktop.
Save ianmcnally/fc0d65c3d461b6458c7b to your computer and use it in GitHub Desktop.
Longest palindrome
def longest_palindrome str
palindromes = []
str.split('').each.with_index do |c, i|
0.upto i do |j|
# get all substrings up to the current letter
chunk = str[j..i]
reverse_chunk = chunk.reverse
# check if they're a palindrome
palindromes << chunk if chunk == reverse_chunk
end
end
palindromes.max_by(&:length)
end
if __FILE__ == $0
require 'test/unit'
class TestLongestPalindrome < Test::Unit::TestCase
def test_simple
assert_equal('aba', longest_palindrome('aba'))
end
def test_two
assert_equal('aba', longest_palindrome('abaa'))
end
def test_three
assert_equal('anana', longest_palindrome('banana'))
end
def test_four
assert_equal('racecar', longest_palindrome('racecar'))
end
def test_five
assert_equal('aba', longest_palindrome('cabad'))
end
def test_six
assert_equal('fuf', longest_palindrome('qwertyuiopfuflkjhgfdsamnbvcxz'))
end
end
end
@ianmcnally
Copy link
Author

I won't be winning any awards for efficiency, but it works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment