125. Valid Palindrome

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

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:

Input: "race a car"
Output: false

Solution

双指针

Complexity

O(N) O(1)

Code

class Solution {
    public boolean isPalindrome(String s) {
        if(s == null || s.length() == 0)
            return true;
        s = s.toLowerCase();
        int i = 0, j = s.length() - 1;
        while(i < j){
            while(!isAlphanumeric(s.charAt(i)) && i < j){
                i++;
            }
            while(!isAlphanumeric(s.charAt(j)) && i < j){
                j--;
            }
            if(s.charAt(i) != s.charAt(j)){
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
    
    public boolean isAlphanumeric(char a){
        if((a>='a' && a <='z') || (a>='0' && a<='9'))
            return true;
        return false;
    }
}