- Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: “A man, a plan, a canal: Panama”
Output: true
Example 2:
Input: “race a car”
Output: false
python
class Solution:
def isPalindrome(self, s: str) -> bool:
res = "".join(re.findall("[a-zA-Z0-9]*",s)).lower()
return res == res[::-1]
java:
class Solution {
public boolean isPalindrome(String s) {
if(s==null)
return false;
if(s.length() == 0)
return true;
int low = 0,high = s.length() -1;
s = s.toLowerCase();
while(low<high){
while (low < high && !Character.isLetterOrDigit(s.charAt(low)))
low++;
while (low < high && !Character.isLetterOrDigit(s.charAt(high)))
high--;
if(s.charAt(high)!=s.charAt(low))
return false;
low++;
high--;
}
return true;
}
}