AC这道题目的时候,当判断是否是相同的isalphanumeric(数字字母)时,我的写法是if((i<=j) && (s.charAt(i) - s.charAt(j) != 0) && (Math.abs(s.charAt(i) - s.charAt(j)) != 32))
最后testcase"0P"不能通过,最后发现0和P的ascII码确实仅差32;最后改为:if((i<=j) && ((i<=j) && (s.charAt(i) - s.charAt(j) != 0) && (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))))
code:
public class Solution125 {
//判断回文最快的方法
public boolean isPalindrome(String s) {
if(s.length() == 0) {
return true;
}
int i = 0,j = s.length() - 1;
while(i < j) {
while((i < j) && !isalphanumeric(s.charAt(i))){
++i;
}
while((i < j) && !isalphanumeric(s.charAt(j))){
--j;
}
//deal with "a."的情形;
if(i >= j) {
break;
}
//System.out.println(s.charAt(i) - s.charAt(j));
if((i <= j) && (s.charAt(i) - s.charAt(j) != 0) && (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j)))) {
return false;
}else{
++i;
--j;
}
}
return true;
}
public boolean isalphanumeric(char c) {
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c<= '9'));
}
}
other‘s code:
package leetcode;
public class Solution125Other {
public boolean isPalindrome(String s) {
if(s == null){
return false;
}
if(s.length() < 2) {
return true;
}
char[] charArray = s.toCharArray();
int len = s.length();
int i = 0;
int j = len-1;
while(i < j) {
char left,right;
while(i < len-1 && !isAlpha(charArray[i]) && !isNum(charArray[i])) {
i++;
left = charArray[i];
}
while(j > 0 && !isAlpha(charArray[j]) && !isNum(charArray[j])){
--j;
right = charArray[j];
}
if(i >= j) {
break;
}
left = charArray[i];
right = charArray[j];
if(!isSame(left,right)) {
return false;
}
++i;
--j;
}
return true;
}
private boolean isSame(char left, char right) {
// TODO Auto-generated method stub
if(isNum(left) && isNum(right)){
return left == right;
}else if(isAlpha(left) && isAlpha(left)){
return Character.toLowerCase(left) == Character.toLowerCase(right);
}else{
return false;
}
}
private boolean isNum(char c) {
// TODO Auto-generated method stub
return c >= '0' && c <= '9';
}
private boolean isAlpha(char c) {
// TODO Auto-generated method stub
return (c >= 'a' && c <= 'z')||(c >= 'A' && c <= 'Z');
}
public static void main(String[] args) {
}
}