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

 

Approach #1: Character + String. [Java]

    public boolean isPalindrome(String s) {
        if (s == null) return true;
        String temp = s.replaceAll("[^a-zA-Z0-9]", "");
        int n = temp.length();
        for (int l = 0, r = n-1; l <= r; ++l, --r) {
            if (Character.toLowerCase(temp.charAt(l)) != Character.toLowerCase(temp.charAt(r)))
                return false;
        }
        return true;
    }

  

Approach #2: Make Map. [Java]

    private static final char[] charMap = new char[256];
    static {
        for (int i = 0; i < 10; ++i) 
            charMap[i+'0'] = (char)(1 + i);
        for (int i = 0; i < 26; ++i)
            charMap[i+'a'] = charMap[i+'A'] = (char)(11 + i);
    }
    
    public boolean isPalindrome(String s) {
        char[] pChars = s.toCharArray();
        int start = 0, end = pChars.length - 1;
        char cs, ce;
        while (start < end) {
            cs = charMap[pChars[start]];
            ce = charMap[pChars[end]];
            if (cs != 0 && ce != 0) {
                if (cs != ce) return false;
                start++;
                end--;
            } else {
                if (cs == 0) start++;
                if (ce == 0) end--;
            }
        }
        return true;
    }

  

Reference:

https://stackoverflow.com/questions/8248277/how-to-determine-if-a-string-has-non-alphanumeric-characters

https://www.tutorialspoint.com/java/lang/character_tolowercase.htm

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

https://leetcode.com/problems/valid-palindrome/discuss/39993/3ms-java-solution(beat-100-of-java-solution)

 

posted @ 2019-04-15 14:40  Veritas_des_Liberty  阅读(156)  评论(0编辑  收藏  举报