Suppose you're developing a text editor with a feature that checks if a sentence or word is a palindrome. A palindrome reads the same backward as forward, such as "madam" or "racecar". This feature can help users check if their inputs are valid palindromes, which is particularly useful in certain puzzles or coding challenges.
Problem statement
Given a string, write a Python function to determine if it is a valid palindrome. The string can contain letters, numbers, and other characters, but we only consider alphanumeric characters and ignore cases.
Sample input
1s = "A man, a plan, a canal: Panama"
Sample output
1output = True
Idea to solve
To check if a string is a valid palindrome:
- Ignore non-alphanumeric characters and convert all letters to the same case.
- Compare the cleaned string with its reverse.
Full code
Here's the complete Python code to check if a string is a valid palindrome:
1import re
2
3def is_valid_palindrome(s):
4 # Remove non-alphanumeric characters and convert to lowercase
5 cleaned_str = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
6
7 # Compare the cleaned string with its reverse
8 return cleaned_str == cleaned_str[::-1]
9
10# Sample input
11s = "A man, a plan, a canal: Panama"
12# Calling the function and printing the result
13output = is_valid_palindrome(s)
14print("Is the string a valid palindrome?", output)
Explanation of the code
- Import re Module: We import the re module to use regular expressions for removing non-alphanumeric characters.
- Cleaning the String: We use re.sub(r'[^a-zA-Z0-9]', '', s) to remove all characters that are not letters or numbers. We then convert the string to lowercase using .lower().
- Comparison: We compare the cleaned string with its reverse (cleaned_str[::-1]). If they are equal, the string is a valid palindrome.
- Function Call: We call the is_valid_palindrome function with the sample input and print the result.
Time complexity
The time complexity of this approach is O(n), where n is the length of the string. This is because we need to iterate over the string to clean it and then compare it with its reverse.
Frequently Asked Questions
Sign-in First to Add Comment
Leave a comment 💬
All Comments
No comments yet.