Last active
August 29, 2015 14:25
-
-
Save xemoe/bcf4ac45512a55d6b371 to your computer and use it in GitHub Desktop.
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 | |
// | |
// Testing on: | |
// PHP 5.6.10-1+deb.sury.org~vivid+1 (cli) | |
// | |
function palindrome($string) | |
{ | |
ksort($counter = count_chars($string, 1)); | |
$ret = ''; | |
$mid = ''; | |
$hasOdd = 0; | |
foreach ($counter as $char => $count) { | |
if ($count&1) { | |
if (++$hasOdd > 1) { | |
return 'imp'; | |
} | |
$mid = str_repeat(chr($char), $count); | |
} else { | |
$ret .= str_repeat(chr($char), $count/2); | |
} | |
} | |
return sprintf('%s%s%s', $ret, $mid, strrev($ret)); | |
} | |
assert('imp' == palindrome('abcd')); | |
assert('cddc' == palindrome('cdcd')); | |
assert('ccddaddcc' == palindrome('daccdccdd')); | |
assert('!3?ABabbaBA?3!' == palindrome('AABBaabb33!!??')); | |
assert('!3?ABabSSSbaBA?3!' == palindrome('AASSSBBaabb33!!??')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment