125 Valid Palindrome
Question
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.
ASCII: [A-Z]:65-90, [a-z]:97-122
Character.isLetterOrDigit() Character.isLetter()
public class Solution { public boolean isPalindrome(String s) { if (s.length() == 0) { return true; }
int f = 0, e = s.length()-1;
s = s.toUpperCase();
while (f < e) {
if (!Character.isLetterOrDigit(s.charAt(f))) {
f++;
continue;
}
if (!Character.isLetterOrDigit(s.charAt(e))) {
e--;
continue;
}
if (s.charAt(f) != s.charAt(e)) {
return false;
}
f++;
e--;
}
return true;
}
}
updated(12.18.15)
public class Solution {
public boolean isPalindrome(String str) {
//becasue we need to ignoring something and compare from two end, so we need two pointers
if (str == null) {
return true;
}
str = str.trim();
if (str.length() == 0) {
return true;
}
// toLowerCase(), return string.
str = str.toLowerCase();
int i = 0, j = str.length() - 1;
while (i < j) {
// continue相当于说,必须满足我才能进行循环的其他项,否则就连续先保证满足我。
// 审题不认真,没注意只关心字母。
if (!Character.isLetterOrDigit(str.charAt(i))) {
i++;
continue;
}
if (!Character.isLetterOrDigit(str.charAt(j))) {
j--;
continue;
}
if (str.charAt(i) != str.charAt(j)) {
return false;
}
// 看到循环,一定提醒自己写终止条件
i++;
j--;
}
return true;
}
}