Is Palindrome
Given a string s, return true if it is a palindrome, otherwise return false.
A palindrome is a string that reads the same forward and backward. It is also case-insensitive and ignores all non-alphanumeric characters.
Example 1:
Input: s = "Was it a car or a cat I saw?"
Output: true
Explanation: After considering only alphanumerical characters we have “wasitacaroracatisaw”, which is a palindrome.
Example 2:
Input: s = "tab a cat"
Output: false
Explanation: “tabacat” is not a palindrome.
Constraints:
1 <= s.length <= 1000
s is made up of only printable ASCII characters.
Solution
Easy problem! First, we need to filter all non-alphanumeric characters out. Then just check if this string is a palindrome one character by one character.
Oh, because palindrome is case-insensitive, we can convert the string into lower case at very first.
Code
To appear like an expert, we can use regular expression to find all alpha and numeric characters.
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
alphanumeric_string = ''.join(re.findall(r'[a-z0-9]+', s))
for i in range(len(alphanumeric_string)//2):
if alphanumeric_string[i] != alphanumeric_string[-1-i]:
return False
return True

678

被折叠的 条评论
为什么被折叠?



