Problem Link:
http://oj.leetcode.com/problems/valid-palindrome/
The following two conditions would simplify the problem:
- only alphanumerci characters considered
- ignoring cases
Given a string, we check if it is a valid palindrome by following rules:
- An empty string is a valid palindrome;
- Letter case should be ignored;
- Blank space should be ignored;
- The string is a valid palindrome only if s[x] == s[n-x] for x = 0,1,..., n/2
Therefore, we design the algorithm that scan the string from both the beginning and the end. Each iteration, we compare them to check if the string is a valid palindrome so far.
The algorithm will terminate if the two characters are not same; when all the characters in the string are compared, the algorithm will return True.
The following code is the python code accepted by oj.leetcode.com.
class Solution:
# @param s, a string
# @return a boolean
n0 = ord('0')
n9 = ord('9')
A = ord('A')
Z = ord('Z')
def isAlphanumeric(self, c):
x = ord(c)
return ( self.n0 <= x <= self.n9 or \
self.A <= x <= self.Z ) def isPalindrome(self, s):
"""
Scan the string from two ends of the string
"""
low = 0
high = len(s)-1
s = s.upper()
while low <= high:
if not self.isAlphanumeric(s[low]):
low += 1
elif not self.isAlphanumeric(s[high]):
high -= 1
elif s[low] == s[high]:
low += 1
high -= 1
else:
return False
return True