1. 程式人生 > >LeetCode刷題Easy篇Valid Palindrome判斷字串是否迴文

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;
            
        }
}