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

Source: leetcode | Difficulty: EASY
Tags: String algorithms

Amortized analysis

Starter code: class Solution:
    def isPalindrome(self, s: str) -> bool:
        

Solutions:
class Solution:

	def isPalindrome(self, s):
		cleanlist = [c for c in s.lower() if c.isalnum()]
		return cleanlist == cleanlist[::-1]


class Solution:

	def isPalindrome(self, s):
		s = [symbol for symbol in s.lower() if 'a' <= symbol <= 'z' or '0' <= symbol <= '9']
		return s == s[::-1]


class Solution:

	def isPalindrome(self, s):
		s = s.strip().lower()
		if s == '':
			return True
		wordsR = []
		for item in s:
			if item.isalnum() == True:
				wordsR.append(item)
		if wordsR == []:
			return True
		words = wordsR[:]
		wordsR.reverse()
		if words == wordsR:
			return True
		else:
			return False


class Solution:

	def isPalindrome(self, s):
		b = 0
		t = len(s) - 1
		while b < t:
			while b < t and (not s[b].isalnum()):
				b = b + 1
			while b < t and (not s[t].isalnum()):
				t = t - 1
			if s[b].lower() != s[t].lower():
				return False
			b = b + 1
			t = t - 1
		return True


class Solution:

	def isPalindrome(self, s):
		if len(s) == 0:
			return True
		pt1 = 0
		pt2 = len(s) - 1
		while pt1 < pt2:
			while pt1 < pt2 and (not s[pt1].isalnum()):
				pt1 = pt1 + 1
			while pt1 < pt2 and (not s[pt2].isalnum()):
				pt2 = pt2 - 1
			if pt1 < pt2 and s[pt1].lower() != s[pt2].lower():
				return False
			pt1 = pt1 + 1
			pt2 = pt2 - 1
		return True


class Solution:

	def isPalindrome(self, s):
		(left, right) = (0, len(s) - 1)
		while left < right:
			while left < len(s) and (not s[left].isalnum()):
				left += 1
			while right >= 0 and (not s[right].isalnum()):
				right -= 1
			if left >= len(s) or right < 0:
				return True
			if s[left].lower() != s[right].lower():
				return False
			left += 1
			right -= 1
		return True


class Solution:

	def isPalindrome(self, s):
		i = 0
		j = len(s) - 1
		while i < j:
			while i <= len(s) - 1 and (not s[i].isalnum()):
				i += 1
			while j >= 0 and (not s[j].isalnum()):
				j -= 1
			if i < j and s[i].lower() != s[j].lower():
				return False
			i += 1
			j -= 1
		return True


class Solution:

	def isPalindrome(self, s):
		s = s.lower()
		i = 0
		j = len(s) - 1
		while i < j:
			if not self._is_alphanumeric(s[i]):
				i += 1
				continue
			if not self._is_alphanumeric(s[j]):
				j -= 1
				continue
			if s[i] != s[j]:
				return False
			i += 1
			j -= 1
		return True

	def _is_alphanumeric(self, c):
		if ord(c) >= 97 and ord(c) <= 122 or (ord(c) >= 48 and ord(c) <= 57):
			return True