Write a function named isPalindrome
that determines whether a given string is a palindrome.
A string
is considered a palindrome if it reads the same forward and backward, ignoring spaces, punctuation, and capitalization. To check if a string is a palindrome, first sanitize it by removing unwanted characters and converting it to the same case. Then, compare the sanitized string with its reverse.
To check if a string is a palindrome without using built-in reverse functions, follow these steps:
-
Check for Empty or Null Input
If the string is empty or null, returntrue
directly or handle it as a special case (empty strings are generally considered palindromes). -
Sanitize the String
Ignore spaces, punctuation, and capitalization:-
Remove all non-alphanumeric characters.
-
Convert all characters to lowercase.
-
-
Compare Characters from Both Ends
Use a loop with two pointers:-
One starting from the beginning.
-
One from the end.
Compare corresponding characters while moving inward.
-
-
Return Result
If all characters match, returntrue
; otherwise, returnfalse
.
Pseudocode:
Function isPalindrome(s):
Initialize an empty string cleanString
For each character ch in s:
If ch is alphanumeric:
Append lowercase of ch to cleanString
Set reversedString = reverse of cleanString
If cleanString is equal to reversedString:
Return true
Else:
Return false