GitHub地址
题目
- 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
- Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
说明
- 本题中,我们将空字符串定义为有效的回文串。
- For the purpose of this problem, we define empty string as valid palindrome.
示例
示例 1:
- 输入: “A man, a plan, a canal: Panama”
- 输出: true
示例 2:
- 输入: “race a car”
- 输出: false
代码
这一题我觉得是双向指针的题,一开始的代码是下面的。
public static boolean isPalindrome(String s) {
if (s.length() == 1) return true;
String lowerCase = s.toLowerCase();
int i = 0, j = lowerCase.length() - 1;
while (i <= j) {
char chi = lowerCase.charAt(i);
char chj = lowerCase.charAt(j);
while (chi < '0'|| (chi > '9' && chi <'a') || chi >'z') {
i++;
if (i > j) return true;
chi = lowerCase.charAt(i);
}
while (chj < '0'|| (chj > '9' && chj <'a') || chj >'z') {
j--;
if (i > j) return true;
chj = lowerCase.charAt(j);
}
if (chi != chj) return false;
i++;
j--;
}
return true;
}
AC之后,参考别人的代码,把自己的代码优化了一下,大致思路是一样的
public boolean isPalindrome2(String s) {
String lowerCase = s.toLowerCase();
int i = 0, j = lowerCase.length() - 1;
while (i <= j) {
char chi = lowerCase.charAt(i);
char chj = lowerCase.charAt(j);
if (isNotValidChar(chi)) {
i++;
} else if (isNotValidChar(chj)) {
j--;
} else if (chi != chj) {
return false;
} else {
i++;
j--;
}
}
return true;
}
public boolean isNotValidChar(char ch) {
return ch < '0'|| (ch > '9' && ch <'a') || ch >'z';
}