官方地址
https://leetcode-cn.com/problems/valid-palindrome/
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
解法一 自顶向下
class Solution {
public boolean isPalindrome(String s) {
s = filterNonNumbersAndCharacters(s);
return reverse(s).equalsIgnoreCase(s);
}
private String filterNonNumbersAndCharacters(String s) {
return s.replaceAll("[^A-Za-z0-9]", "");
}
private String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
}
解法二
class Solution {
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
if (left < right) {
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) return false;
left++;
right--;
}
}
return true;
}
}
class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s)-1
while l < r:
while l<r and not s[l].isalnum():
l+=1
while l<r and not s[r].isalnum():
r-=1
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return True