Input:
s = "A man, a plan, a canal: Panama"
Output:
true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
1
2
3
4
5
Input:
s = "race a car"
Output:
false
Explanation: "raceacar" is not a palindrome.
Example 3:
1
2
3
4
5
6
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.
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;
}