1. 驗證迴文串
雙指針:定義左、右雙指針,向中間判斷;跳過非數字字母的字符;將字母全部轉化爲小寫再判斷。
class Solution {
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) {
return true;
}
char[] chs = s.toCharArray();
int l = 0;
int r = s.length() - 1;
while (l <= r) {
if (!isValid(chs[l])) {
l++;
continue;
}
if (!isValid(chs[r])) {
r--;
continue;
}
if (Character.toLowerCase(chs[l]) != Character.toLowerCase(chs[r])) {
return false;
}
l++;
r--;
}
return true;
}
private boolean isValid(char ch) {
if ('0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z') {
return true;
} else {
return false;
}
}
}
2. 迴文數
轉化爲字符串:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
StringBuilder sb = new StringBuilder();
while (x != 0) {
sb.append(x % 10);
x = x / 10;
}
for (int i = 0; i < (sb.length() + 1) / 2; i++) {
if (sb.charAt(i) != sb.charAt(sb.length() - 1 - i)) {
return false;
}
}
return true;
}
}
除餘運算:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
if (x / div != x % 10) {
return false;
}
x = x % div / 10;
div /= 100;
}
return true;
}
}
翻轉後半部分:
循環終止條件:前半部分小於等於後半部分時,翻轉剛好一半或者過半。
判斷相等:數字總長度爲偶數時,直接判斷前後是否相等;數字長度爲奇數時,中間數字位於後半部分的最低位上,除十再比較。
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || x % 10 == 0 && x != 0) {
return false;
}
int y = 0;
while (x > y) {
y = y * 10 + x % 10;
x = x / 10;
}
return x == y || x == y / 10;
}
}