Leetcode题解 125. Valid Palindrome

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.

选出字符串中的字母,按照顺序,反序构造两个堆栈,然后依次弹出元素判断是否相同。因为如果一个串是回文串,那么这个串翻转180度后应该还是这个串本身。所以每次弹出的元素应该相同。

public  boolean isPalindrome(String s) {
        char forw;
        char back;
        Stack<Character> forward = new Stack<Character>();
        Stack<Character> backward = new Stack<Character>();
        for (int i = 0; i < s.length(); i++) {
            if (isAlpha(s.charAt(i))) {
                forward.push(s.charAt(i));
            }
        }
        for (int i = s.length() - 1; i >= 0; i--) {
            if (isAlpha(s.charAt(i))) {
                backward.push(s.charAt(i));
            }
        }
        while (backward.size() > 0) {
            forw = forward.pop();
            back = backward.pop();
            if (toUpper(forw) != toUpper(back)) {
                return false;
            }
        }
        return true;
    }

    private  boolean isAlpha(char c) {
        if ((c > 47 && c < 58) || (c > 64 && c < 91) || (c > 96 && c < 123)) {
            return true;
        }
        return false;
    }

    private  char toUpper(char c) {
        if ('A' <= c && c <= 'Z') {
            return (char) (c + 32);
        } else {
            return c;
        }
    }

你可能感兴趣的:(LeetCode)