125. Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Solution:Check by two pointers from head&end

skip non-alphanumeric before checking
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    public boolean isPalindrome(String s) {
        if(s == null || s.isEmpty()) return true;
        int start = 0, end = s.length() - 1;
        while(start < end) {
            while(start < end && !Character.isLetterOrDigit(s.charAt(start))) start++;
            while(start < end && !Character.isLetterOrDigit(s.charAt(end))) end--;
            
            if(Character.toLowerCase(s.charAt(start)) == Character.toLowerCase(s.charAt(end))) {
                start++;
                end--;
            }
            else {
                return false;
            }
        }
        return true;
    }
}

你可能感兴趣的:(125. Valid Palindrome)