回文数 - litonghui/TechBlog GitHub Wiki

回文数

指一个词或短句它的字符首位和末尾,第二位和倒数第二位,等等知道中间一位,两两相同,其中字符指英文单词和数字,例如:

"A man, a plan, a canal: Panama" is a palindrome.

"race a car" is not a palindrome.

"v' 5:UxU:5 v'" is a palindrome.

"OP" is a not palindrome.

分析题目要求:单词或者短语中,有大写和小写,统一为小写字母,如果有特殊符号,比如" ",";","、","等等,需要去除掉,然后首尾逐个比较。

方法一:创建一个 char [] 数组 word,遍历单词或者短语,在过程中把大写转换为小写,去除掉所有特殊字符,其次对新的word 数组首位元素比较,直到中间位置,如果相同则为回文,否则不是。

方法二:直接遍历单词或者短语字符串,在遍历过程中满足英文单词和数字再比较是否相同,否则地位++或者高位--跳过比较下一个,直到中间位置,如果相同则为回文,否则不是。

public boolean isPalindrome(String s) {
    boolean isPalindrome = true;
    if (s != null && !"".equals(s)) {
        int low = 0, height = s.length() - 1;
        s = s.toLowerCase();
        while (low < height) {
            if (((s.charAt(low) >= 'a' && s.charAt(low) <= 'z') || (s.charAt(low) >= '0' && s.charAt(low) <= '9'))
                    && ((s.charAt(height) >= 'a' && s.charAt(height) <= 'z') || (s.charAt(height) >= '0' && s.charAt(height) <= '9'))) {
                if (s.charAt(low) == s.charAt(height)) {
                    low++;
                    height--;
                    continue;
                } else {
                    isPalindrome = false;
                    break;
                }
            }
            if (!((s.charAt(low) >= 'a' && s.charAt(low) <= 'z') || (s.charAt(low) >= '0' && s.charAt(low) <= '9'))) {
                low++;
                continue;
            }
            if (!(s.charAt(height) >= 'a' && s.charAt(height) <= 'z') || (s.charAt(height) >= '0' && s.charAt(height) <= '9')) {
                height--;
                continue;
            }
        }
    }
    return isPalindrome;
}