题目描述
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.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
判断一个字符串是否是回文字符串。解题思路
看到题目,立马想到到的思路是:
遍历字符串,将字符串中的非字母和数字去掉,并将大写字母转成小写字母。在这一遍扫描中,我么可以到到两个字符串,一个是经上述处理的,一个是经上述处理并逆转的。比较这两个字符串是否相等即可得到待判定的字符串是否是回文字符串。
但是,提交代码后,返回的是
超时!!!!!
这是为什么呢?想了一会儿终于明白,实际上我们根不不需要遍历字符串,我们只需要将首尾的字符进行比较即可决定它不是回文字符串的情况,而最坏的情况,只需要遍历字符串长度的1/2即可。
代码
需要针对首尾字符的不同组合情况进行判断,只有当首尾字符均是字母或数字时,才比较它们是否相等,如果不相等立即返回false。
public static boolean isPalindrome(String s) {
if (s == null)
return false;
if (s.equals(" ") || s.equals(""))
return true;
int leftCur = 0;
int rightCur = s.length() - 1;
while (leftCur < rightCur) {
char head = s.charAt(leftCur);
char tail = s.charAt(rightCur);
if (isNum(head) && isNum(tail)) {
if (head == tail) {
leftCur++;
rightCur--;
} else {
return false;
}
} else if (isAlpha(head) && isAlpha(tail)) {
if (head == tail || Math.abs(head - tail) == 'a' - 'A') {
leftCur++;
rightCur--;
} else {
return false;
}
} else if ((isNum(head) && isAlpha(tail))
|| (isNum(tail) && isAlpha(head))) {
return false;
} else {
if (!(isNum(head) || isAlpha(head))) {
leftCur++;
}
if (!(isNum(tail) || isAlpha(tail))) {
rightCur--;
}
}
}
return true;
}
判断字符是否是字母
public static boolean isAlpha(char ch) {
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
return true;
}
return false;
}
判断字符是否是数字
public static boolean isNum(char ch) {
if (ch >= '0' && ch <= '9') {
return true;
}
return false;
}