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.

思路: 两指针分别从两头往中间找,挨个比较。
注意用到Java Character的API,在此列举下:

Method Description
boolean isLetter(char ch)
boolean isDigit(char ch)
char toUpperCase(char ch)
char toLowerCase(char ch)
boolean isUpperCase(char ch)
boolean isLowerCase(char ch)
boolean isWhitespace(char ch)

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

    public boolean isLetterOrDigit(char s) {
        return Character.isLetter(s) || Character.isDigit(s);
    }



}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s