aboutsummaryrefslogtreecommitdiff
path: root/valid_palindrome.py
blob: 2b361e0b2a5678b42675fcc373254fc6de5d1380 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 125. Valid Palindrome

"""
a phrase is a palindrome if, after converting all uppercase letters into
lowercase letters, and removing all non-alphanumeric characters, it reads the
same forward and backward. alphanumeric characters include only letters and
numbers. given a string 's', return true if it is a palindrome, or false
otherwise.
"""


class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        l, r = 0, len(s) - 1
        while l < r:
            while l < r and not s[l].isalnum():
                l += 1
            while l < r and not s[r].isalnum():
                r -= 1
            if s[l].lower() != s[r].lower():
                return False
            l += 1
            r -= 1
        return True


if __name__ == "__main__":
    obj = Solution()
    print(obj.isPalindrome(s="A man, a plan, a canal: Panama"))
    print(obj.isPalindrome(s="race a car"))
    print(obj.isPalindrome(s=" "))