[lintcode easy]Valid Palindrome

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.

Challenge

O(n) time without extra memory.

 

//// consider the lowercase

 

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();
        
        char[] c=s.toCharArray();
        int len=s.length();
        
        int left=0;
        int right=len-1;
        
        while(left<right)
        {
            if(!isValid(c[left]))
            {
                left++;
            }
            
            if(!isValid(c[right]))
            {
                right--;
            }
            
            if(c[left]!=c[right] && left<right)
            {
                return false;
            }
            else
            {
                left++;
                right--;
            }
        }
        return true;
        
    }
    
    public boolean isValid(char c)
    {
        if(c<='z'&&c>='a') return true;
        if(c>='0'&&c<='9') return true;
        return false;
    }
}

 

posted on 2015-12-02 02:40  一心一念  阅读(108)  评论(0编辑  收藏  举报

导航