Valid Palindrome(125 Easy)

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.

这道题的几个点,

一就是alphanumeric characters and ignoring cases,字母和数字,忽略大小写。

二就是考虑空字符串是否为回文,最好在面试时候问下面试官,这里是认为空字符串是回文。

 public boolean isPalindrome(String s) {
    int length = s.length();
    if (length == 0 || length == 1) return true;

    int start  = 0;
    int end = length - 1;

    while (start < end) {
        // determine if the char is an alphanumeric
        while ((start < end) && (!isAlphaNum(s.charAt(start)))) start++;
        while ((start < end) && (!isAlphaNum(s.charAt(end)))) end--;

        // check if lower case
        Character lStart = s.charAt(start);
        Character lEnd = s.charAt(end);
        if (!Character.isLowerCase(lStart)) lStart = Character.toLowerCase(lStart);
        if (!Character.isLowerCase(lEnd)) lEnd = Character.toLowerCase(lEnd);

        if (lStart.equals(lEnd)) {
            start++;
            end--;
        } else {
            return false;
        }
    }
    return true;
}

private boolean isAlphaNum(char ch) {
    return (Character.isLetter(ch) || Character.isDigit(ch)) ? true : false;
}

results matching ""

    No results matching ""