title: Valid Palindrome
tags:
- valid-palindrome
- No.125
- simple
- string
- regular
Description
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
Corner Cases
""
"a"
","
Solutions
Regular Expression
Use regular expression to filter any non-target characters and replace CAPTIAL CHARACTERS with lower ones. Then verify the palindrome as before.
The running time is O(n) for the verification part.
class Solution {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
s = s.replaceAll("[^a-z0-9]", "");
if (s.equals("")) {return true;}
boolean flag = true;
int len = s.length();
for (int i=0; i<len/2+1; i++) {
flag = flag && (s.charAt(i) == s.charAt(len-i-1));
}
return flag;
}
}