乐闻世界logo
搜索文章和话题

Implement a function to check if a string is a palindrome

2024年6月24日 16:43

A palindrome is a string that reads the same forwards and backwards. For example, 'madam' or 'racecar' are palindromes.

Here is a simple Python function to check if a string is a palindrome:

python
def is_palindrome(s): # First, convert the string to lowercase and remove non-alphanumeric characters clean_s = ''.join(c for c in s.lower() if c.isalnum()) # Then compare the processed string with its reversed version return clean_s == clean_s[::-1]

In this function, we first convert the input string to lowercase and remove all non-alphanumeric characters, focusing only on letters and digits while ignoring punctuation and whitespace. Then we compare the processed string with its reversed version to determine if it is a palindrome.

Let's test this function with some examples:

python
print(is_palindrome("Madam")) # outputs True print(is_palindrome("racecar")) # outputs True print(is_palindrome("hello")) # outputs False print(is_palindrome("A man, a plan, a canal, Panama")) # outputs True

In the last example, although the original string contains spaces and punctuation, in our is_palindrome function, these characters are removed, resulting in the string 'amanaplanacanalpanama', which is a palindrome.

标签:JavaScript算法