class Solution {
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) return true;
s = s.toLowerCase();
int lo = 0, hi = s.length() - 1;
while (lo <= hi) {
Character c1 = s.charAt(lo), c2 = s.charAt(hi);
if (!Character.isLetterOrDigit(c1)) {
lo++;
}
else if (!Character.isLetterOrDigit(c2)) {
hi--;
}
else {
if (c1 != c2) {
return false;
}
lo++;
hi--;
}
}
return true;
}
}
- The idea is to use two pointers to check respective left and right characters. Skip all non-alphanumeric characters.
- time O(n) space O(1)