Palindrome Checker
Write a Javascript function that determines if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, ignoring spaces, punctuation, and capitalization. This is a fundamental problem in string manipulation, useful for various text processing tasks.
Problem Description
Your task is to create a Javascript function named isPalindrome that accepts a single string argument. This function should return true if the string is a palindrome and false otherwise.
Key Requirements:
- The function must ignore case sensitivity. For example, "Racecar" should be considered a palindrome.
- The function must ignore any non-alphanumeric characters (spaces, punctuation, etc.). For example, "A man, a plan, a canal: Panama" should be considered a palindrome.
- The function should handle empty strings and strings with only one character.
Expected Behavior:
- For a valid palindrome string, the function returns
true. - For a string that is not a palindrome, the function returns
false.
Edge Cases to Consider:
- Empty strings (
""). - Strings with a single character (
"a"). - Strings containing only non-alphanumeric characters (
".,!"). - Strings with mixed casing and punctuation.
Examples
Example 1:
Input: "level"
Output: true
Explanation: "level" reads the same forwards and backwards.
Example 2:
Input: "hello"
Output: false
Explanation: "hello" reads "olleh" backwards, which is different.
Example 3:
Input: "A man, a plan, a canal: Panama"
Output: true
Explanation: After removing non-alphanumeric characters and converting to lowercase, the string becomes "amanaplanacanalpanama", which is a palindrome.
Example 4:
Input: ""
Output: true
Explanation: An empty string is conventionally considered a palindrome.
Example 5:
Input: "a"
Output: true
Explanation: A single character string is a palindrome.
Constraints
- The input
strwill be a string. - The length of the input string
strcan range from 0 to 1000 characters. - The solution should be efficient, aiming for a time complexity of O(n), where n is the length of the string.
Notes
Consider how you can preprocess the input string to handle the case insensitivity and non-alphanumeric character requirements. There are several common approaches to solving this problem, such as reversing the string or using two pointers. Think about which method might be most straightforward and efficient given the constraints.