Question
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
“A man, a plan, a canal: Panama” is a palindrome.
“race a car” is not a palindrome.
code
/**
* 常规解法
*
* @param s
* @return
*/
public boolean isPalindrome(String s) {
StringBuilder res = new StringBuilder();
for (char t : s.toLowerCase().toCharArray()) {
if ((t >= '0' && t <= '9') || (t >= 'a' && t <= 'z')) {
res.append(t);
}
}
return res.toString().equals(res.reverse().toString());
}
/**
* 左右指针
*
* @param s
* @return
*/
public boolean isPalindromeP(String s) {
if (s == null) {
return false;
}
int len = s.length();
int left = 0;
int right = len - 1;
s = s.toLowerCase();
while (left < right) {
if (!Character.isLetterOrDigit(s.charAt(left))) {
left++;
} else if (!Character.isLetterOrDigit(s.charAt(right))) {
right--;
} else if (s.charAt(left) != s.charAt(right)) {
return false;
} else {
left++;
right--;
}
}
return true;
}
本文介绍了一种用于判断字符串是否为回文的有效方法,重点在于只考虑字母数字字符且忽略大小写。通过两种不同的实现方式——常规解法和双指针技术进行详细解释。
270

被折叠的 条评论
为什么被折叠?



