bailuo

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

  

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.

Java:

public class Solution {
    public boolean isPalindrome(String s)
    {
        int a = 0, b = s.length()-1;
        if (s == null || s.length() == 0) {
            return true;
        }
        while(a < b)
        {
            if(!isAlphanumeric(s.charAt(a)))
            {
                a++;
            }else if (!isAlphanumeric(s.charAt(b))){
                b--;
            }else if (Character.toLowerCase(s.charAt(a)) == Character.toLowerCase(s.charAt(b))) {
                a++;
                b--;
            }else {
                return false;
            }
        }
         return true;
        
    }
    public boolean isAlphanumeric(char ch)
    {
        if (ch <= 'z' && ch >= 'a' || ch <= 'Z' && ch >= 'A' || ch <= '9'  && ch >= '0') {
            return true;    
        }
        return false;
    }
}

这一题跟一般的回文判断不同之处是,该题的回文字符不是连续的,或者说不是纯数字和字符,其中夹杂了很多空格符或者标点,所以我们在这里把判断条件抽象成一个判断函数,在双向遍历的时候直接调用,这样我们只需要一遍就能够判断该字符串是否是回文的了。

posted on 2014-10-17 15:48  bailuo  阅读(123)  评论(0)    收藏  举报