回文数

题目:

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.
Example Questions Candidate Might Ask:
Q: What about an empty string? Is it a valid palindrome?
A: For the purpose of this problem, we define empty string as valid palindrome.

 

解答:

使用两个游标

public boolean isPalindrome(String s) {
    int i = 0;
    int j = s.length()-1;
    while(i < j) {
        while(i < j && !Character.isLetterOrDigit(s.charAt(i))) {
            i++;
        }

        while(i < j && !Character.isLetterOrDigit(s.charAt(j))) {
            j--;
        }

        if(Character.toLowerCase(s.charAt(j) != Character.toLowerCase(s.charAt(i))) {
            return false;
        }

        i++;
        j--;
    }

    return true;
}

 

posted @ 2019-02-01 16:28  林木声  阅读(105)  评论(0编辑  收藏  举报