Created
December 12, 2011 19:02
-
-
Save basvandorst/1468595 to your computer and use it in GitHub Desktop.
PHP: Find 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
<?php | |
/** | |
* Easy way to find the longest palindrome in a string | |
* | |
* Solution for: http://challenge.greplin.com/ | |
* The Greplin Programming Challenge: Version 1 | |
* | |
* @author Bas van Dorst <[email protected]> | |
*/ | |
$data = "FourscoreracecarsthatandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"; | |
for($i=0; $i<strlen($data); $i++ ) | |
{ | |
$palindrome = true; | |
$offset = 1; | |
while($palindrome) | |
{ | |
$word = substr($data, $i-$offset, ($offset*2)+1 ); | |
if( $word == strrev($word) ) { | |
print strlen($word) .' '. $word.'<br />'; | |
} else { | |
$palindrome = false; | |
} | |
$offset++; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is not working for simple input like "abba" or "abbac"