Created
June 30, 2014 17:28
-
-
Save ianmcnally/fc0d65c3d461b6458c7b to your computer and use it in GitHub Desktop.
Longest palindrome
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I won't be winning any awards for efficiency, but it works!