/**
* 给定一个字符串,判断是否是回文字符串(只考虑数字和字母,忽略大小写)
* <p>
* Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
* <p>
* Example 1:
* <p>
* Input: s = "A man, a plan, a canal: Panama"
* Output: true
* Explanation: "amanaplanacanalpanama" is a palindrome.
* <p>
* Example 2:
* <p>
* Input: s = "race a car"
* Output: false
* Explanation: "raceacar" is not a palindrome.
* <p>
* Constraints:
* <p>
* 1 <= s.length <= 2 * 10^5
* s consists only of printable ASCII characters.
*/
public class _125_ValidPalindrome {
public static void main(String[] args) {
String s = "A man, a plan, a canal: Panama";
System.out.println(isPalindrome(s));
s = "race a car";
System.out.println(isPalindrome(s));
s = "0P";
System.out.println(isPalindrome(s));
}
public static boolean isPalindrome1(String s) {
char[] chars = s.toLowerCase().toCharArray();
int l = 0;
int r = chars.length - 1;
while (l < r) {
if (!((chars[l] >= 'a' && chars[l] <= 'z') || (chars[l] >= '0' && chars[l] <= '9'))) {
l++;
continue;
}
if (!((chars[r] >= 'a' && chars[r] <= 'z') || (chars[r] >= '0' && chars[r] <= '9'))) {
r--;
continue;
}
if (chars[l] != chars[r]) {
return false;
}
l++;
r--;
}
return true;
}
/**
* LeetCode评论区解法之一
*/
public static boolean isPalindrome(String s) {
int l = 0;
int r = s.length() - 1;
while (l < r) {
char chL = s.charAt(l);
if (!Character.isLetterOrDigit(chL)) {
l++;
continue;
}
char chR = s.charAt(r);
if (!Character.isLetterOrDigit(chR)) {
r--;
continue;
}
if (chL >= 'A' && chL <= 'Z') {
chL = Character.toLowerCase(chL);
}
if (chR >= 'A' && chR <= 'Z') {
chR = Character.toLowerCase(chR);
}
if (chL != chR) {
return false;
}
l++;
r--;
}
return true;
}
}
/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */