Created
May 12, 2020 18:53
-
-
Save bad-mushroom/01d5e40041ca2b4de44fc28fb3fcee2e to your computer and use it in GitHub Desktop.
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 | |
function isPalindrome(string $word): bool | |
{ | |
$hashMap = []; | |
for ($i = 0; $i < strlen($word); $i++) { | |
if (isset($hashMap[$word{$i}])) { | |
$hashMap[$word{$i}] = $hashMap[$word{$i}] + 1; | |
} else { | |
$hashMap[$word{$i}] = 1; | |
} | |
} | |
$odds = 0; | |
foreach ($hashMap as $char) { | |
if ($char % 2 !== 0 ) { | |
$odds++; | |
if ($odds > 1) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
$words = [ | |
'bob', | |
'a', | |
'aa', | |
'aaa', | |
'aba', | |
'abba', | |
'abcba', | |
'racceccar', | |
'aab', | |
'aabb', | |
'acbba', | |
'acccbbb', | |
]; | |
foreach ($words as $word) { | |
$result = isPalindrome($word); | |
$val = ($result === true) ? 'true' : 'false'; | |
echo ($word . ' is ' . $val . "\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment