Intern
Which method allows recognizing palindromes?
sobes.tech AI
Answer from AI
There are several approaches.
-
Comparing the string with its reverse:
function isPalindrome(string $str): bool { $cleanedStr = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str)); // Remove punctuation and convert to lowercase return $cleanedStr === strrev($cleanedStr); } -
Two-pointer traversal of the string:
function isPalindromeTwoPointers(string $str): bool { $cleanedStr = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str)); $length = strlen($cleanedStr); $left = 0; $right = $length - 1; while ($left < $right) { if ($cleanedStr[$left] !== $cleanedStr[$right]) { return false; } $left++; $right--; } return true; } -
Using a for loop:
function isPalindromeForLoop(string $str): bool { $cleanedStr = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str)); $length = strlen($cleanedStr); $middle = floor($length / 2); for ($i = 0; $i < $middle; $i++) { if ($cleanedStr[$i] !== $cleanedStr[$length - 1 - $i]) { return false; } } return true; }
All three methods have their advantages. The first is the most concise. The second and third can be slightly more efficient for very long strings, as they do not require creating a full copy of the reversed string. A regular expression is used to clean the string from characters that are not letters or digits, and strtolower ensures case-insensitive comparison.