Last active
June 2, 2019 22:14
-
-
Save anushshukla/012e4d544450eccee54efd10ec91fda5 to your computer and use it in GitHub Desktop.
Check if string is palindrome (case insensitive)
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 | |
// 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