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.

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.

public class Solution {
    public boolean isPalindrome(String s) {
        if(s=="")return true; 
        s=s.toLowerCase();
        int len=s.length();
        int begin=0,end=len-1;
        while(begin<end){
            while(!valid(s.charAt(begin))){
                ++begin;
                if(begin>=end) return true;
            }
            while(!valid(s.charAt(end))){
                --end;
                if(begin>=end) return true;
            }
            if(s.charAt(begin)==s.charAt(end)){
                begin++;
                end--;
            }else return false;            
        }
        return true;
        
    }
    Boolean valid(char c){
        if(c>='0'&&c<='9')return true;
        if(c>='a'&&c<='z')return true;
        return false;
    }
}

注意:java遍历字符串使用charAt方法。此代码使用了库函数toLowerCase方法。

     注意空串的处理

你可能感兴趣的:(ROM)