Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Last active June 2, 2019 22:14
Show Gist options
  • Save anushshukla/012e4d544450eccee54efd10ec91fda5 to your computer and use it in GitHub Desktop.
Save anushshukla/012e4d544450eccee54efd10ec91fda5 to your computer and use it in GitHub Desktop.
Check if string is palindrome (case insensitive)
<?php
// Complexity: O(n/2)
function isPalindrome($str) {
$array = str_split($str);
$arrayLen = sizeof($array) - 1;
foreach ($array as $index => $currChar) {
$indexFromBehind = $arrayLen - $index;
$charFromBehind = $array[$indexFromBehind];
$charFromBehindLowerCase = strtolower($charFromBehind);
$currCharLowserCase = strtolower($currChar);
if ($currCharLowserCase !== $charFromBehindLowerCase) return false;
$pivotIndex = $arrayLen / 2;
$reachedPivotIndex = $index === $arrayLen / 2;
if ($reachedPivotIndex) break;
}
return true;
}
var_dump(isPalindrome('dad'));
var_dump(isPalindrome('mom'));
var_dump(isPalindrome('ohhohho'));
var_dump(isPalindrome('ohhohhO'));
var_dump(isPalindrome('ohhohhOk'));
var_dump(isPalindrome('Deleveled'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment