Leetcode[125] Valid Palindrome
09 Nov 2015###Task1 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.
Note: Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
###Python ####Complex
import re
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
s = re.sub("[^a-zA-Z0-9]", "", s).lower()
if len(s) == 0:
return True
mid = len(s) / 2
for i in range(mid + 1):
if s[i] != s[-1 - i]:
return False
return True
####Simple
import re
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
if len(s) == 0:
return True
start = 0
end = len(s) - 1
while start < end:
while start < end and not s[start].isalnum():
start += 1
while start < end and not s[end].isalnum():
end -= 1
if s[start].lower() != s[end].lower():
return False
start += 1
end -= 1
return True
###Java
public class Solution {
public boolean isPalindrome(String s) {
if (s == null) {
return false;
}
if (s.length() == 0) {
return true;
}
s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
int start = 0;
int end = s.length() - 1;
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}
###Points
- String: .lower() ; .upper()
- Java use s.replaceAll(regex, “”); Python use re.sub(regex, “”, s). Where re = regular expression, sub = substitution
- s.isalnum() = is alphabetic and number
- Similar: isalpha() isdigit()