Skip to content

Instantly share code, notes, and snippets.

@mthelander
Created January 10, 2012 04:14
Show Gist options
  • Save mthelander/1586892 to your computer and use it in GitHub Desktop.
Save mthelander/1586892 to your computer and use it in GitHub Desktop.
palindrome finder
# 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