Skip to content

Instantly share code, notes, and snippets.

@bad-mushroom
Created May 12, 2020 18:53
Show Gist options
  • Save bad-mushroom/01d5e40041ca2b4de44fc28fb3fcee2e to your computer and use it in GitHub Desktop.
Save bad-mushroom/01d5e40041ca2b4de44fc28fb3fcee2e to your computer and use it in GitHub Desktop.
<?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