Skip to content

Instantly share code, notes, and snippets.

@bbwharris
Created August 16, 2012 14:16
Show Gist options
  • Save bbwharris/3370397 to your computer and use it in GitHub Desktop.
Save bbwharris/3370397 to your computer and use it in GitHub Desktop.
Naive Longest Palindrome
# Not the fastest, but working
def longest_palindrome(input_string)
# default to the first letter, so we return 'a' palindrome if none found
palindrome = input_string.first
max = input_string.size
# Windows over possible substrings and tests for a palindrome
max.downto(0) do |last|
0.upto(max) do |first|
substring = input_string.slice(first..last)
reversed = substring.reverse
if substring == reversed && substring.length > palindrome.length
palindrome = substring
end
end
end
return palindrome
end
#Simple tests:
longest_palindrome("asdfjfdkljadfabbafjfdldkfhguoenbbhegh")
#> "fabbaf"
longest_palindrome("Brandon Harris")
#> rr
longest_palindrome("nothinginthis")
#> n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment