LeetCode刷题Easy篇Valid Palindrome判断字符串是否回文

题目

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

我的解法

很简单,两个指针就搞定了,代码如下,一次通过,注意一些character的api,是否相等?大小写转换?是否数字和字符?三个api不太熟悉

class Solution {
    public boolean isPalindrome(String s) {
        int p=0;
        int q=s.length()-1;
        while(p<=q){
           Character leftChar=s.charAt(p);
           Character rightChar=s.charAt(q);
            if(!Character.isLetterOrDigit(leftChar)){
                p++;
                continue;
            }
            if(!Character.isLetterOrDigit(rightChar)){
                q--;
                continue;
            }
            if(Character.toLowerCase(leftChar)!=(Character.toLowerCase(rightChar))){
                    return false;
            }
            p++;
            q--;
        }
        return true;
            
        }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/84884787