DEV Community

WhereIsLijah
WhereIsLijah

Posted on

125. Valid Palindrome

Topic: Arrays & Hashing

Soln 1 (isalnum):

A not so efficient solution:

  1. create a new list to store the palindrome
  2. loop through the characters in the string:
  3. check if it is alphanumeric, if it is then append to list
  4. assign a variable, then convert palindrome list to string
  5. assign another variable, then reverse palindrome
  6. return and compare both variables
def isPalindrome(self, s: str) -> bool:
    palin = []

    for c in s:
        if c.isalnum():
            palin.append(c.lower())
    x = ''.join(palin)
    y = x[::-1]

    return x == y
Enter fullscreen mode Exit fullscreen mode

Soln 2 (isalnum):

  1. Filter and Normalize: Create palindrome by joining all alphanumeric characters from s and converting them to lowercase.

  2. Check Palindrome: Return True if palindrome is equal to its reverse, otherwise return False.

def isPalindrome(self, s: str) -> bool:
        palindrome = ''.join(filter(str.isalnum, s)).lower()
        return palindrome == palindrome[::-1]
Enter fullscreen mode Exit fullscreen mode

Notes: Attempt to understand 2 pointer solution.

Top comments (0)