版权声明:本文为博主原创文章,未经博主允许不得转载。
难度:容易
要求:
给定一个字符串,判断其是否为一个回文串。只包含字母和数字,忽略大小写。
注意事项
你是否考虑过,字符串有可能是空字符串?这是面试过程中,面试官常常会问的问题。
在这个题目中,我们将空字符串判定为有效回文。
样例
"A man, a plan, a canal: Panama" 是一个回文。"race a car" 不是一个回文。
思路:
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) {
return true;
}
s = s.toLowerCase();
int left = 0;
int right = s.length() - 1;
while(left < right){
while(left < s.length() && !isValid(s.charAt(left))){// nead to check range of a/b
left++;
}
if(left == s.length()){// for emtpy string “.,,,”
return true;
}
while(right >= 0 && !isValid(s.charAt(right))){
right--;
}
if(Character.toLowerCase(s.charAt(left)) == Character.toLowerCase(s.charAt(right))){
right--;
left++;
}else{
break;
}
}
return right <= left;
}
/**
* 是否为有效
*/
private boolean isValid(char c){
return Character.isLetter(c) || Character.isDigit(c);
}