lintcode-easy-Valid Palindrome

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

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

"race a car" is not a palindrome.

public class Solution {
    /**
     * @param s A string
     * @return Whether the string is a valid palindrome
     */
    public boolean isPalindrome(String s) {
        // Write your code here
        if(s == null || s.length() == 0)
            return true;
        
        s = s.toLowerCase();
        
        int left = 0;
        int right = s.length() - 1;
        
        while(left < right){
            while(left < right && !valid(s.charAt(left)))
                left++;
            while(left < right && !valid(s.charAt(right)))
                right--;
            
            if(s.charAt(left) != s.charAt(right))
                return false;
            else{
                left++;
                right--;
            }
        }
        
        return true;
    }
    
    public boolean valid(char c){
        return (c >= 'a' && c <= 'z') || (c >= '0' && c <='9');
    }
    
}

 

posted @ 2016-03-10 06:46  哥布林工程师  阅读(136)  评论(0编辑  收藏  举报