Valid Palindrome, Leetcode 解题笔记

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.

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.

很简单,two pointers从前后对比解决问题,这道题的考点主要在于字母,数字的判断。

public class Solution{
    public boolean isPalindrome(String s) {
         if (s==null){
             return false;
         }   
         
         if (s.length()==0){
             return true;
         }
         
         s=s.toLowerCase();
         
         int left=0;
         int right=s.length()-1;
         
         while(left<right){
           
            // Skip all invalid character
             while(left<right && !isValid(s.charAt(left)))
             { 
                 left++;
             }
              // Skip all invalid character
             while( left<right && !isValid(s.charAt(right)))
             {
                 right--;
             }
             
             if (s.charAt(left)!=s.charAt(right)) return false;
             
             
             left++;
             right--;
         }
         
         return true;
    }
    //  check if current character is valid
    private boolean isValid(char c){
        if ('a'<=c && c<='z') return true;
        
        if ('0'<=c && c<='9') return true;
        
        return false;
    }
}
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