LeetCode 125. Valid Palindrome



Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false


A palindrome, and its reverse, are identical to each other.

Python Solution

class Solution:
    def isPalindrome(self, s: str) -> bool:
        i = 0
        j = len(s) - 1
        s = s.lower()

        left = ""
        right = ""
        for i in range(0, len(s)):
            if s[i].isalpha() or s[i].isdigit():
                left += s[i]

        for j in range(len(s) - 1, -1, -1):
            if s[j].isalpha() or s[j].isdigit():
                right += s[j]

        return left == right
  • Time complexity: O(N).
  • Space complexity: O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *