Valid Palindrome

Problem

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

Example

"A man, a plan, a canal: Panama" is a palindrome.

"race a car" is not a palindrome.

Note

Have you consider that the string might be empty? This is a good question to ask during an interview.

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

重点是.toLowerCase()Character.isLetterOrDigit()两个函数的使用;
以及指针在标点情况下移动后的continue语句。

Challenge

O(n) time without extra memory. ----> 指针嘛。

Solution

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

Update 2018-9

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

linspiration
161 声望53 粉丝