Valid Palindrome

Written by

Python

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s1 = [c.lower() for c in s if c.isalnum()]
        return s1 == s1[::-1]
sol = Solution()
print(sol.isPalindrome("dad")) 
# True

The time complexity is O(n) and the space complexity is O(n), where n is the length of the input string s.

Alternate solution

class Solution:
    def isPalindrome(self, s: str) -> bool:
        temp = []
        for c in s:
            if c.isalnum():
                temp.append(c.lower())
        s="".join(temp)
        low, high = 0, len(s)-1
        while low<high:
            if s[low]!=s[high]:
                return False
            low+=1
            high-=1
        return True