【LeetCode OJ】Valid Palindrome

Posted on 2014-04-21 02:56  卢泽尔  阅读(159)  评论(0)    收藏  举报

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:

  1. An empty string is a valid palindrome;
  2. Letter case should be ignored;
  3. Blank space should be ignored;
  4. 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