Check Whether a String Reads the Same Both Ways

easy string two pointers

Problem

Treat the string as containing only its alphanumeric characters in lowercase; ignore everything else. Decide whether what remains reads the same forwards and backwards.

Two pointers walk in from both ends. They each skip over non-alphanumeric characters; whenever they land on real characters, those characters must match. If the pointers cross without a mismatch, it is a palindrome.

Inputs = "Madam, I'm Adam."
Outputtrue
Stripped + lowercased: "madamimadam".

def is_palindrome(s):
    l, r = 0, len(s) - 1
    while l < r:
        while l < r and not s[l].isalnum():
            l += 1
        while l < r and not s[r].isalnum():
            r -= 1
        if s[l].lower() != s[r].lower():
            return False
        l += 1
        r -= 1
    return True
function isPalindrome(s) {
  let l = 0, r = s.length - 1;
  const ok = c => /[a-z0-9]/i.test(c);
  while (l < r) {
    while (l < r && !ok(s[l])) l++;
    while (l < r && !ok(s[r])) r--;
    if (s[l].toLowerCase() !== s[r].toLowerCase()) return false;
    l++; r--;
  }
  return true;
}
class Solution {
    public boolean isPalindrome(String s) {
        int l = 0, r = s.length() - 1;
        while (l < r) {
            while (l < r && !Character.isLetterOrDigit(s.charAt(l))) l++;
            while (l < r && !Character.isLetterOrDigit(s.charAt(r))) r--;
            if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r)))
                return false;
            l++; r--;
        }
        return true;
    }
}
bool isPalindrome(const string& s) {
    int l = 0, r = (int)s.size() - 1;
    while (l < r) {
        while (l < r && !isalnum((unsigned char)s[l])) l++;
        while (l < r && !isalnum((unsigned char)s[r])) r--;
        if (tolower((unsigned char)s[l]) != tolower((unsigned char)s[r]))
            return false;
        l++; r--;
    }
    return true;
}
Time: O(n) Space: O(1)