Problem Description

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 letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

  • Input: s = "A man, a plan, a canal: Panama"
  • Output: True
  • Explanation: “amanaplanacanalpanama” is a palindrome.

Example 2:

  • Input: s = "race a car"
  • Output: false
  • Explanation: “raceacar” is not a palindrome.

My Idea

First we pre-process the string to a lower-case alphanumeric one. Then we use the classic two pointer approach with one pointer starting at the beginning and one at the end of the string and comparing the values. If there’s a mismatch, we return False, else the word is a palindrome.

My solution

# Time Complexity: O(n)
def isPalindrome(s: str) -> bool:
    str = ''.join(ch for ch in s if ch.isalnum()).lower()
    print(str)
    for i, j in zip(range(0,(len(str)//2)), range(len(str)-1,len(str)//2-1,-1)):
        if str[i]!=str[j]:
            return False
    return True