Sunday, September 14, 2014

Leetcode (Python): Valid Palindrome

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.

Solution:

class Solution:
    # @param s, a string
    # @return a boolean
    def isPalindrome(self, s):
        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 start<end and s[start].lower() != s[end].lower():
                return False
            start +=1
            end -= 1
        return True

1 comment :

  1. You could just do this def reverse(string):
    l = len(string)
    new_str = []
    rev_str = string[::-1]
    for i in reversed(range(l)):
    new_str.append(string[i])
    val = ''.join(new_str)
    print("v%s" % val)
    print("r%s" % rev_str)
    if string == rev_str:
    return "palidrome"
    else:
    return "No"
    s = reverse("A man, a plan, a canal: Pdfanama")
    print(s)

    And of course check for empty string - add that as a separate check.

    ReplyDelete