A few days ago we looked at palindromic numbers. A palindrome is a string that reads the same forwards as it does backwards. Our goal today is to write a function that takes in a string and returns the longest palindrome in that string.
For example, the longest palindrome in "Max drives a racecar after work" is "a racecar a".
Fun fact: This can be solved in linear time o(n), though a naive, quadratic solution is perfectly fine
Comments:
Anonymous - 10 years, 9 months ago
My Solution in C++
include "afx.h"
int ReverseCompare(CString* String, int SLength);
void main(void) { printf("Please write your String and the program will search for the longest palindrome!\n"); CString String; scanf("%[^\t\n]", String); String.Format("%s", String); for(int i=String.GetLength();i>=1;i--) {
if(int found = ReverseCompare(&String,i)) { printf("The longest palindrome found in your String is \"%s\"!\n", String.Mid(found,i)); return; }
}
int ReverseCompare(CString* String1, int SLength) { CString String1temp, String2temp; int StrLength = String1->GetLength(); int nOffset = StrLength - SLength; do { String2temp = String1temp = String1->Mid(nOffset,SLength); String2temp.MakeReverse(); if(!String1temp.CompareNoCase(String2temp)) return nOffset; else nOffset--;
}
reply permalink
Anonymous - 10 years, 9 months ago
reply permalink
Pearce Keesling - 10 years, 9 months ago
I'm really curious to know what the proper way to do it is. I'm sure my way is extremely inefficient, but better than nothing ;).
C++ if you couldn't guess :)
reply permalink
Max Burstein - 10 years, 9 months ago
Thanks for posting! A really good write up on the problem can be found here http://www.akalin.cx/longest-palindrome-linear-time (python). The wikipedia page also has a pretty good explanation http://en.wikipedia.org/wiki/Longest_palindromic_substring (java).
reply permalink
Pearce Keesling - 10 years, 9 months ago
That was a great read, thanks :)
reply permalink
Asandwich - 10 years, 9 months ago
My solution in Java. I'm not to sure of runtime, I think it's the quadratic solution.
reply permalink
tehmagik - 10 years, 9 months ago
Here's a python version:
reply permalink
Anonymous - 10 years, 9 months ago
Short one in J.
reply permalink
Anonymous - 10 years, 9 months ago
Seems like I had misunderstood the requirements. Here's a better one.
reply permalink
John - 10 years, 9 months ago
I think I got a linear solution in javascript, but it could be a BAD linear solution, but it's one map and one reduce.
Usage: longestPalindromeIn("Max drives a racecar after work"); // "a racecar a"
PS, you can hit F12, and copy/paste mine to the console to test it right on the page.
reply permalink
Hueho - 10 years, 9 months ago
In Ruby
reply permalink
gulliver - 10 years, 9 months ago
reply permalink