準(zhǔn)備開始刷題,然后希望把做過的題寫在這里,這樣既能加深印象,又能有機(jī)會(huì)找出自己潛在的問題。
題目如下:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Notice
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.
解題代碼如下:
思路很簡單,就是設(shè)置兩個(gè)指針,一個(gè)頭一個(gè)尾,一直對(duì)比到中間,如果遇到不一樣就return false。
當(dāng)然,題目還要求忽略空格和數(shù)字,所以這題需要用到Character對(duì)象的方法, 這個(gè)時(shí)間久遠(yuǎn)不用可能會(huì)忘,所以需要認(rèn)真看一下。
public class Solution {
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
// Write your code here
if( s.length() == 0){
return true;
}
int left = 0;
int right = s.length()-1;
while(left < right){
if(!Character.isLetter(s.charAt(left)) && !Character.isDigit(s.charAt(left))){
left++;
continue;
}
if(!Character.isLetter(s.charAt(right)) && !Character.isDigit(s.charAt(right))){
right--;
continue;
}
if(Character.toUpperCase(s.charAt(left++)) != Character.toUpperCase(s.charAt(right--))){
return false;
}
}
return true;
}
}