不計非字母數字的元素和大小寫,判斷是否是回文字符串。
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. 定義:空string也是回文。
For the purpose of this problem, we define empty string as valid palindrome.
注意:
- 1.非字母數字的元素處理
- 空string
- 字符串里的數字要加' ' 這個小錯誤導致一直報錯。
- s.replaceAll("\\W", "") 這個方法可以直接把不合法字符刪除。
\\w*是正則表達式.
\\w表示的是數字或字母。 * 的意思表示零個或多個。
因此\\w* 表示的是任意個數字或字母組合。
Runtime: 9 ms
class Solution {
public boolean isPalindrome(String s) {
int len = s.length();
if(len == 0) return true;
s = s.toLowerCase();
for(int i =0, j = len-1; i< j;i++,j--){
while(!isValidChar(s.charAt(i)) && i<j) i++;
while(!isValidChar(s.charAt(j)) && i<j) j--;
if(s.charAt(i) != s.charAt(j) ) return false;
}
return true;
}
private boolean isValidChar(char x){
return ((x >= '0' && x <= '9' ) || (x >= 'a' && x <= 'z')) ;
}
}