0125. Valid Palindrome

https://leetcode.com/problems/valid-palindrome

Description

Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Example 1:

**Input:** s = "A man, a plan, a canal: Panama"
**Output:** true
**Explanation:** "amanaplanacanalpanama" is a palindrome.

Example 2:

**Input:** s = "race a car"
**Output:** false
**Explanation:** "raceacar" is not a palindrome.

Constraints:

  • 1 <= s.length <= 2 * 105

  • s consists only of printable ASCII characters.

ac1: 2 pointers

class Solution {
    public boolean isPalindrome(String s) {
        // input check and edge cases
        if (s == null) return false;
        if (s.length() <= 1) return true;

        // 2 pointers
        s = s.toLowerCase();
        int l = 0, r = s.length() - 1;
        while (l < r) {
            while (l < r && !valid(s.charAt(l)) ) l++;
            while (l < r && !valid(s.charAt(r)) ) r--;
            if (s.charAt(l) != s.charAt(r)) return false;
            l++;
            r--;
        }

        return true;
    }

    private boolean valid(char c) {
        if (c >= 'a' && c <= 'z'
           || c >= '0' && c <= '9') {
            return true;
        }
        return false;
    }
}

Last updated