Input: s ="A man, a plan, a canal: Panama"Output: trueExplanation: "amanaplanacanalpanama"is a palindrome.
Example 2:
1
2
3
Input: s ="race a car"Output: falseExplanation: "raceacar"is not a palindrome.
Example 3:
1
2
3
4
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
From start and end loop though the string, i.e., char array. If it is not alpha or number, increase or decrease pointers. Compare the alpha and numeric characters. The solution below is pretty straightforward.
classSolution {
publicbooleanisPalindrome(String s) {
// Preprocess the string using regex: remove non-alphanumeric characters and convert to lowercase String cleaned = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
// Compare the cleaned string with its reversereturn cleaned.equals(new StringBuilder(cleaned).reverse().toString());
}
}
1
2
3
4
5
6
7
classSolution:
defisPalindrome(self, s: str) -> bool:
# Preprocess the string using regex cleaned = re.sub(r"[^a-zA-Z0-9]", "", s).lower() # Remove non-alphanumeric characters and convert to lowercase# Compare the cleaned string with its reversereturn cleaned == cleaned[::-1]
Method 1 - Removing non-alphanumeric chars and Using 2 Pointers#
publicbooleanisPalindrome(String s) {
if (s ==null) {
returntrue;
}
if (s.length()<2) {
returntrue;
}
int n = s.length();
int i = 0; // left pointerint j = n - 1; // right pointerwhile (i<j) {
// note upper bound is r and not n// this improves time complexity a bitwhile (i < j &&!isAlphaNum(s.charAt(i))) {
i++;
}
while (j > i &&!isAlphaNum(s.charAt(j))) {
j--;
}
if (i >= j)
break;
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
returnfalse;
}
i++;
j--;
}
returntrue;
}