LeetCode(125)——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

 

AC:

public boolean isPalindrome(String s) {
        if (s == null || s.length() < 2) {
            return true;
        }
        
        int left = 0;
        int right = s.length() - 1;
        char[] chars = s.toLowerCase().toCharArray();
        
        while (left < right) {
            while (left < right && !isValidChar(chars[left])) {
                left++;
            }
            
            while (left < right && !isValidChar(chars[right])) {
                right--;
            }
            
            if (chars[left] == chars[right]) {
                left++;
                right--;
            } else {
                return false;
            }
        }
        
        return true;
    }
    
    private boolean isValidChar(char ch) {
        if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) {
            return true;
        }
        
        return false;
    }

當然也可以用Character來判斷是否合法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章