問(wèn)題:
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.
大意:
給出一個(gè)字符串,判斷它是不是回文,只考慮大小寫(xiě)字母和數(shù)字,忽略大小寫(xiě)。
例子:
"A man, a plan, a canal: Panama" 是回文。
"race a car" 不是回文。
注意:
你有考慮字符串可能為空嗎?這是面試時(shí)的一個(gè)好問(wèn)題。
對(duì)于這道題的目的,我們假設(shè)空字符串也是有效的回文。
思路:
又是一道判斷回文的題目,不同的是這道題只判斷字符串中的大小寫(xiě)字母和數(shù)字,從例子中也可以看出,空格和其他標(biāo)點(diǎn)符號(hào)都跟沒(méi)看到一樣,也就是在做的時(shí)候要忽略,另外大小寫(xiě)字母忽略,看做是相同的,這也就意味著在判斷是否相同時(shí)要將大小寫(xiě)字母轉(zhuǎn)為同一個(gè)格式。
由于要先判斷一個(gè)字符是不是數(shù)字或者大小寫(xiě)字母,我們做一個(gè)方法來(lái)專(zhuān)門(mén)檢測(cè)這個(gè)事情,避免主體代碼太冗長(zhǎng)。
在主體代碼中,我們用兩個(gè)指針,一個(gè)從頭開(kāi)始遍歷,一個(gè)從末尾開(kāi)始遍歷,當(dāng)頭尾都找到字母或者數(shù)字后,就進(jìn)行對(duì)比是否是相同的,有不同說(shuō)明不是回文,否則就是回文,在比較時(shí)我們將大寫(xiě)字母都轉(zhuǎn)化成小寫(xiě)來(lái)對(duì)比,當(dāng)然也可以反過(guò)來(lái)。
代碼(Java):
public class Solution {
public boolean isLetterOrDigit(char test) {
if ((test - '0' >= 0 && test - '0' <= 9) || (test - 'a' >= 0 && test - 'a' <= 25) || (test - 'A' >= 0 && test - 'A' <= 25)) return true;
else return false;
}
public boolean isPalindrome(String s) {
if (s.length() == 0) return true;
int i = 0;
int k = s.length() - 1;
while (i <= k) {
char tempI = s.charAt(i);
char tempK = s.charAt(k);
if (!isLetterOrDigit(tempI)) i++;
else if (!isLetterOrDigit(tempK)) k--;
else {
if (Character.toLowerCase(tempI) != Character.toLowerCase(tempK)) return false;
else {
i++;
k--;
}
}
}
return true;
}
}
合集:https://github.com/Cloudox/LeetCode-Record