判断String是否为palindrome:Two Pointers(left & right) 同时边扫边check 当前两边的char是否相同
code
public boolean isValidPalindrome(String s){
int l = 0;
int r = s.length() - 1;
while (l < r){
if(s.charAt(l) != s.charAt(r)){
return false;
}else{
l++;
r--;
}
}
return true;
}
判断number是否为palindrome:先reverse original number 变为reversed number ,再判断 original number == reversed number ?
code
public boolean isPalindrome(int x) {
// handle input is negative like -121 or end with 0
if (x < 0 || (x != 0 && x % 10 == 0)) return false; int temp = x;
int reverseInt = 0;
while (x != 0) {
reverseInt = reverseInt * 10 + x % 10;
x = x / 10;
}
return (reverseInt == temp);
}