beats 80.01 %
class Solution {
public boolean isPalindrome(String s) {
if (s == null || s.length() <= 1) return true;
int left = 0;
int right = s.length() - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
left++;
}
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
right--;
}
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}
二刷
Character.isLetter()
Character.isDigit()
Character.toLowerCase()
Character.toUpperCase()
Runtime: 4 ms, faster than 81.04% of Java online submissions for Valid Palindrome.
Memory Usage: 44 MB, less than 42.12% of Java online submissions for Valid Palindrome.
class Solution {
public boolean isPalindrome(String s) {
// We can create two pointers to scan toward each other
// If a non-alphanumeric character is encountered, then skip that character
if (s == null || s.equals("")) {
return true;
}
// l r
// A man, a plan, a canal: Panama
int left = 0, right = s.length() - 1;
while (left < right) {
while (left < right && !isAlphanumeric(s, left)) {
left++;
}
while (left < right && !isAlphanumeric(s, right)) {
right--;
}
if (left < right && Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
private boolean isAlphanumeric(String s, int index) {
char c = s.charAt(index);
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
No comments:
Post a Comment