Created
January 10, 2012 04:14
-
-
Save mthelander/1586892 to your computer and use it in GitHub Desktop.
palindrome finder
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
# Finds longest palindromic substring in O(m*n) time | |
def find_longest_palindrome(string) | |
matrix, s, size = {}, string.reverse, string.size | |
0.upto(size-1) do |x| | |
0.upto(size-1) do |y| | |
matrix[[x,y]] = (matrix[[x-1,y-1]] || 0) + 1 if string[x] == s[y] | |
end | |
end | |
string[matrix.key(m=matrix.values.max).first-m+1, m] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment