Paste_Image.png
My code:
public class Solution {
public boolean isPalindrome(String s) {
if (s == null)
return false;
if (s.length() == 0)
return true;
int head = 0;
int tail = s.length() - 1;
while (head < tail) {
char tempHead = s.charAt(head);
char tempTail = s.charAt(tail);
while (tempHead < 48 || (tempHead > 57 && tempHead < 65)
|| (tempHead > 90 && tempHead < 97) || tempHead > 122) {
head++;
if (head == s.length())
return true;
else
tempHead = s.charAt(head);
}
while (tempTail < 48 || (tempTail > 57 && tempTail < 65)
|| (tempTail > 90 && tempTail < 97) || tempTail > 122) {
tail--;
tempTail = s.charAt(tail);
}
if (tempHead >= 65 && tempHead <= 90) {
if (tempTail >= 65 && tempTail <= 90) {
if (tempHead == tempTail) {
head++;
tail--;
}
else
return false;
}
else if (tempTail > 90) {
if (tempHead == tempTail - 32) {
head++;
tail--;
}
else
return false;
}
else
return false;
}
else if (tempHead > 90) {
if (tempTail >= 65 && tempTail <= 90) {
if (tempHead == tempTail + 32) {
head++;
tail--;
}
else
return false;
}
else if (tempTail > 90) {
if (tempHead == tempTail) {
head++;
tail--;
}
else
return false;
}
else
return false;
}
else {
if (tempHead == tempTail) {
head++;
tail--;
}
else
return false;
}
}
return true;
}
}
My test result:
這道題目比較簡單。主要煩的兩點(diǎn)。
一個是他是大小寫忽略的,要用if語句判斷好這些情況。然后原有的字符串還有數(shù)字。不能有toLowercase 這些方法,太浪費(fèi)時間了,每用一次都要遍歷一次字符串!
第二個是,忽略其他非字母數(shù)字的字符。所以需要里面用兩個while過濾一下。
同時,當(dāng)head跑到字符串尾巴處時,表示該字符串不含數(shù)字字母,就直接返回true就行了。
然后在tail里面不需要考慮這個corner case,因?yàn)槿绻媸沁@樣,才head里面已經(jīng)判斷結(jié)束返回了。
**
總結(jié): String, traversal
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) {
return true;
}
s = s.toLowerCase();
int i = 0;
int j = s.length() - 1;
while (i < j) {
while (i < s.length() && !isValid(s.charAt(i))) {
i++;
}
while (j >= 0 && !isValid(s.charAt(j))) {
j--;
}
if (i >= j) {
break;
}
if (s.charAt(i) != s.charAt(j)) {
return false;
}
else {
i++;
j--;
}
}
return true;
}
private boolean isValid(char c) {
if (c >= '0' && c <= '9') {
return true;
}
else if (c >= 'a' && c <= 'z') {
return true;
}
else {
return false;
}
}
}
感覺這么一年下來,自己寫的代碼水平還是有些進(jìn)步的。。。
之前怎么寫的那么復(fù)雜。。
這道題目最重要的是理解一個單詞:
alphanumeric
文字?jǐn)?shù)字的。
所以我單獨(dú)寫了一個函數(shù)來檢查是否valid
其他就差不多了。
Anyway, Good luck, Good luck, Richardo! -- 09/17/2016