Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Example:
Input: "A man, a plan, a canal: Panama"
Output: true
Input: "race a car"
Output: false
Note:
For the purpose of this problem, we define empty string as valid palindrome.
解釋下題目:
給定一個字符串憔四,只看其中的字母和數(shù)字更卒,字母不區(qū)分大小寫,判斷是不是回文字符串
1. 老老實實做唄
實際耗時:8ms
public boolean isPalindrome(String s) {
char[] a = new char[s.length()];
int len = s.length();
if (0 == len) {
return true;
}
int index = 0;
int charLen = 0;
//第一步慌烧,先去除除了字母數(shù)字以外的字符鲫忍,并把所有的大寫轉成小寫
while (index < len) {
if (isLetter(s.charAt(index)) || isNumber(s.charAt(index))) {
a[charLen++] = Character.toLowerCase(s.charAt(index));
}
index++;
}
//第二步膏燕,回文判斷
for (int i = 0; i < charLen / 2; i++) {
if (a[i] != a[charLen - i - 1]) {
return false;
}
}
return true;
}
/**
* 判斷是否是字母
*
* @param a
* @return true = 是字母
*/
public static boolean isLetter(char a) {
if (0 <= a - 'a' && 26 > a - 'a') {
return true;
}
if (0 <= a - 'A' && 26 > a - 'A') {
return true;
}
return false;
}
/**
* 判斷所給字符是否是0-9這十個數(shù)字
*
* @param num 所給字符
* @return true = 是數(shù)字 false = 不是數(shù)字
*/
public static boolean isNumber(char num) {
if ((0 <= num - '0') && (10 > num - '0')) {
return true;
}
return false;
}
踩過的坑:"0P" 一開始我以為只保留字母......
??思路很簡單,剔除除了字母和數(shù)字以外的別的悟民,生成一個新的數(shù)組坝辫,然后用回文數(shù)的方法進行判斷即可。