lint0415 Valid Palindrome
2019-02-07 本文已影响0人
日光降临
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.只考虑字母数字,并忽略大小写
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.
Example
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Challenge
O(n) time without extra memory.
keyword: 双指针
方法一:
100% test cases passedTotal runtime 180 ms
Your submission beats 96.20% Submissions!
public class Solution {
public boolean isPalindrome(String s) {
int len=s.length();
char lft;
char rht;
if(len==0)
return true;
int lo=0;
int hi=len-1;
while(lo<hi){
lft=s.charAt(lo);
rht=s.charAt(hi);
if(lft<'0' || (lft>'9' && lft<'A') || (lft>'Z' && lft<'a') || lft>'z'){
lo++;
continue;
}
if(rht<'0' || (rht>'9' && rht<'A') || (rht>'Z' && rht<'a') || rht>'z'){
hi--;
continue;
}
if(lft==rht || lft==rht+'a'-'A' || lft==rht-'a'+'A'){
lo++;
hi--;
}else{
return false;
}
}
return true;
}
}
方法二:利用Java库函数
toLowerCase(), Character.isLetterOrDigit()
100% test cases passedTotal runtime 184 ms
Your submission beats 66.60% Submissions!
public class Solution {
public boolean isPalindrome(String s) {
int len=s.length();
char lft;
char rht;
if(len==0)
return true;
int lo=0;
int hi=len-1;
s=s.toLowerCase();
while(lo<hi){
lft=s.charAt(lo);
rht=s.charAt(hi);
if(!Character.isLetterOrDigit(lft)){
lo++;
continue;
}
if(!Character.isLetterOrDigit(rht)){
hi--;
continue;
}
if(lft==rht){
lo++;
hi--;
}else{
return false;
}
}
return true;
}
}