迴文字驗證

原題

  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.算法

題目大意

  給定一個字符串,判斷它是不是迴文字符串,僅考慮字母,而且忽略大小寫。ide

解題思路

  使用首尾指針,分別找到第一個符合條件的位置,進行比較,若是相等就進行下一組比較,不相等就返回false,直到全部的字母都處理完。this

代碼實現

算法實現類spa

public class Solution {
    public boolean isPalindrome(String s) {

        if (s == null) {
            return false;
        }

        int left = 0;
        int right = s.length() - 1;

        int delta = 'A' - 'a';
        char l;
        char r;

        while (left < right) {
            while (left < s.length() && !isAlphanumericCharacters(s.charAt(left))) { // 從左向右找數字與字母
                left++;
            }

            while (right >= 0 && !isAlphanumericCharacters(s.charAt(right))) { // 從右向左找數字與字母
                right--;
            }

            if (left < right) {
                l = s.charAt(left);
                r = s.charAt(right);
                if (l == r || l - r == delta || r - l == delta) {
                    left++;
                    right--;
                } else {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 判斷是不是字母或者數字
     *
     * @param c 待判斷的數字
     * @return 判斷結果
     */
    private boolean isAlphanumericCharacters(char c) {
        return c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z';
    }
}
相關文章
相關標籤/搜索