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: trueExample 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://www.tutorialspoint.com/java/lang/character_tolowercase.htm
永远渴望,大智若愚(stay hungry, stay foolish)