Valid Palindrome [Solution]
This problem assesses your ability to work with strings and handle various characters.
Here’s a Python implementation of the is_valid_palindrome
function to determine if a given string is a palindrome:
def is_valid_palindrome(s: str) -> bool:
"""
Determine if the given string is a palindrome.
Parameters:
- s: Input string.
Returns:
- bool: True if the string is a palindrome, False otherwise.
"""
# Convert the string to lowercase and filter out non-alphanumeric characters
cleaned_s = [char.lower() for char in s if char.isalnum()]
# Check if the cleaned string is a palindrome
return cleaned_s == cleaned_s[::-1]
# Example usage:
s = "AbcbA"
result = is_valid_palindrome(s)
print(result) # Output: True
s = "A man, a plan, a canal: Panama"
result = is_valid_palindrome(s)
print(result) # Output: True
s = "race a car"
result = is_valid_palindrome(s)
print(result) # Output: False
s = ""
result = is_valid_palindrome(s)
print(result) # Output: True
This solution converts the input string to lowercase and filters out non-alphanumeric characters. It then checks if the cleaned string reads the same forward and backward, indicating whether it is a palindrome.
Time Complexity:
The time complexity is O(n)
,
where n
is the length of the input string.
Space Complexity:
The space complexity is also O(n)
due to the creation of the cleaned string.