The code determines if a given string is a palindrome by first extracting only the alphanumeric characters and converting them to lowercase. It then compares the characters at corresponding positions from the start and end of the string. If any pair of characters doesn't match, the string is not a palindrome. Otherwise, if all pairs match, the string is a palindrome. The code assumes ASCII characters in the input string.
class Solution:
def isPalindrome(self, s: str) -> bool:
alphanumeric = ""
for c in s:
if self.isAlphanum(c): # or you can use c.isalnum():
alphanumeric += c.lower()
length = len(alphanumeric)
# we need to check half of string
for i in range(length // 2): # // is floor division operator 10 // 3 = 3
if alphanumeric[i] != alphanumeric[length - i - 1]:
return False
return True
def isAlphanum(self, c):
return (
ord("A") <= ord(c) <= ord("Z")
or ord("a") <= ord(c) <= ord("z")
or ord("0") <= ord(c) <= ord("9")
)
- Time complexity:
The time complexity of the code is
- Space complexity:
The space complexity of the code is also alphanumeric
to store the alphanumeric characters from the input string. The length of the alphanumeric
string can be at most equal to the length of the input string, so the space complexity is linear.