Created
August 16, 2012 14:16
-
-
Save bbwharris/3370397 to your computer and use it in GitHub Desktop.
Naive 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
# 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