給定一個字串,判斷它是否迴文,只考慮數字字母字元並忽略大小寫。
題幹:
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.
備註:面試者可以會問這樣的問題:
問:空字串算是迴文字串嗎?
答:在這個問題裡,我們將空字串運定義為迴文字串。
分析:
palindrome ['pælɪndrəʊm] n.迴文(即正讀反讀都一樣的詞或短語)
step1:定義兩個“指標”i,j——一個為“頭指標”,另一個是“尾指標”。
step2:兩“指標”相向移動,跳過既非字母也非數字的字元,判斷指標位置的字元是否相等。
不相等,返回false。相等繼續移動,直到 i>=j ,返回ture。
跳過既非字母也非數字的字元,用到了 Character.isLetterOrDigit() 方法。
不區分大小寫,所以都轉化為小寫來判斷是否相等,用到了 Character.toLowerCase() 方法。
class Solution {
public boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
while (i < j && !Character.isLetterOrDigit(s.charAt(i)))
i++;
while (i < j && !Character.isLetterOrDigit(s.charAt(j)))
j–;
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
return false;
}
i++;
j–;
}
return true;
}
}