2014年11月5日星期三

[Leetcode] 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.
We each time compare the two ends' character, if they are not the same, it could not be a palindrome. During the process, we need to skip all non alphanumeric characters. Here, we need to pay attention to some corner case, such as all the character is non alphanumeric characters, if we do not check again before we actually compare the two characters, the wrong answer would be given.
    public boolean isPalindrome(String s) {
        if(s.length() == 0)
            return true;
        s = s.toLowerCase();
        int i = 0, j = s.length() - 1;
        while(i < j) {
            while(i < j && !((s.charAt(i) >= '0' && s.charAt(i) <= '9') || (s.charAt(i) >= 'a' && s.charAt(i) <= 'z')))
                i++;
            while(i < j && !((s.charAt(j) >= '0' && s.charAt(j) <= '9') || (s.charAt(j) >= 'a' && s.charAt(j) <= 'z')))
                j--;
            if(i < j && s.charAt(i) != s.charAt(j))
                return false;
            i++; j--;
        }
        return true;
    }

没有评论:

发表评论