
Problem Statement
In the given task, we need to determine if a string, referred to as s
, qualifies as a palindrome after undergoing specific transformations. A palindrome is a sequence that reads the same backward as forward. For the purposes of this task, the transformations involve converting all uppercase letters to lowercase and removing all non-alphanumeric characters, which includes anything other than letters and numbers. The output will be true
if the modified string is a palindrome, and false
otherwise.
Examples
Example 1
Input:
s = "A man, a plan, a canal: Panama"
Output:
true
Explanation:
"amanaplanacanalpanama" is a palindrome.
Example 2
Input:
s = "race a car"
Output:
false
Explanation:
"raceacar" is not a palindrome.
Example 3
Input:
s = " "
Output:
true
Explanation:
s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.
Constraints
1 <= s.length <= 2 * 105
s
consists only of printable ASCII characters.
Approach and Intuition
To solve this problem, let's break down the examples provided and extract the intuition and methodology we can use:
- Convert all uppercase characters in the string to lowercase. This ensures that the comparison is case-insensitive, treating 'A' and 'a' as equivalent.
- Remove all non-alphanumeric characters. This step requires scanning each character in the string and excluding any that are not letters or numbers.
- Check if the resulting string is a palindrome. This can be done by comparing the string to its reverse; if they are the same, the string is a palindrome.
Based on each example:
- Example 1: Clearing all characters that are not alphanumeric and converting the rest to lower case provides a straightforward, long palindrome.
- Example 2: Even after cleaning the input string, the sequence does not read the same forwards and backwards, indicating it isn't a palindrome.
- Example 3: A string composed entirely of spaces results in an empty string after cleaning. Since an empty string trivially reads the same in both directions, it is considered a palindrome.
With these steps and considerations in mind, the implementation can systematically check any input string for its palindrome status post-transformation.
Solutions
- C++
- Java
- C
- JavaScript
- Python
class Solution {
public:
bool checkPalindrome(string str) {
for (int start = 0, end = str.length() - 1; start < end; start++, end--) {
while (start < end && !isalnum(str[start])) start++;
while (start < end && !isalnum(str[end])) end--;
if (tolower(str[start]) != tolower(str[end])) return false;
}
return true;
}
};
The provided C++ function, checkPalindrome
, efficiently determines if a given string is a valid palindrome while disregarding non-alphanumeric characters. Here's a concise explanation of how this function operates:
- It uses two index pointers,
start
andend
, to traverse the string from the beginning and the end simultaneously. - The loop continues until the
start
index is less than theend
index. - Within the loop, both pointers skip any non-alphanumeric characters using nested
while
loops. - It then compares the characters at these indices, after converting them to lowercase, to check if they are the same. If at any point they are not, the function immediately returns
false
. - If the loop completes without finding mismatched characters, the function returns
true
, indicating the string is a palindrome.
This method efficiently handles strings with mixed characters, focusing only on alphanumeric values and ignoring case sensitivity. It ensures that only relevant characters are considered, making the palindrome check robust and accurate.
class Solution {
public boolean checkPalindrome(String str) {
for (int start = 0, end = str.length() - 1; start < end; start++, end--) {
while (start < end && !Character.isLetterOrDigit(str.charAt(start))) {
start++;
}
while (start < end && !Character.isLetterOrDigit(str.charAt(end))) {
end--;
}
if (
Character.toLowerCase(str.charAt(start)) !=
Character.toLowerCase(str.charAt(end))
) return false;
}
return true;
}
}
The provided Java solution defines a method checkPalindrome
to determine whether a given string is a palindrome. Ignore any non-alphanumeric characters and make a case-insensitive comparison. Here's a breakdown of how the method works:
- Iterate over the string from both ends simultaneously with two pointers,
start
andend
. - Increment the
start
pointer if the character atstart
is not a letter or digit. - Decrement the
end
pointer if the character atend
is not a letter or digit. - Compare the characters at
start
andend
after converting them to lowercase. If they are not the same, returnfalse
. - If all comparisons are valid, the loop completes successfully and the method returns
true
, confirming the string is a palindrome.
The approach efficiently checks for a palindrome while disregarding non-alphanumeric characters and handling case differences.
bool checkIfPalindrome(char* str) {
int start = 0;
int end = strlen(str) - 1;
while (start < end) {
while (start < end && !isalnum(str[start])) {
start++;
}
while (start < end && !isalnum(str[end])) {
end--;
}
if (tolower(str[start]) != tolower(str[end])) return false;
start++;
end--;
}
return true;
}
This C program checks if a given string is a palindrome while only considering alphanumeric characters and ignoring cases. The function checkIfPalindrome
takes a character array str
as its parameter. It initializes two pointers, start
and end
, to point to the beginning and the end of the string respectively. The function then uses a while loop to iteratively compare the characters at the start
and end
positions, moving inward.
- The inner loops skip non-alphanumeric characters by incrementing
start
and decrementingend
respectively. - Characters are compared in a case-insensitive manner using the
tolower
function. - If a mismatch is found (characters at
start
andend
are not the same when converted to lowercase), the function immediately returnsfalse
. - If the entire string (or relevant part of it) checks out as symmetric, the function returns
true
.
This approach efficiently validates whether the sanitized version of the input string is a palindrome.
var checkPalindrome = function (str) {
let start = 0;
let end = str.length - 1;
while (start < end) {
while (start < end && !validChar(str[start])) {
start++;
}
while (start < end && !validChar(str[end])) {
end--;
}
if ((str[start] + "").toLowerCase() !== (str[end] + "").toLowerCase())
return false;
start++;
end--;
}
return true;
};
function validChar(ch) {
const code = ch.charCodeAt();
return (
(code >= "a".charCodeAt() && code <= "z".charCodeAt()) ||
(code >= "A".charCodeAt() && code <= "Z".charCodeAt()) ||
(code >= "0".charCodeAt() && code <= "9".charCodeAt())
);
}
This solution determines if a given string is a palindrome by considering only alphanumeric characters and ignoring cases. The process involves the following steps:
- Initialize two pointers,
start
at the beginning of the string andend
at the last character. - Use a
while
loop to movestart
andend
closer to the center of the string, skipping over non-alphanumeric characters. - Check if characters at the
start
andend
positions are the same (ignoring case). If they are not, the function returnsfalse
immediately. - If all valid characters from start to end are palindromic, the function returns
true
.
The validChar
function is used to check if a character is alphanumeric using its ASCII values. This makes the solution efficient by ensuring that only relevant characters are considered in the palindrome check.
class Solution:
def checkPalindrome(self, text: str) -> bool:
left_index, right_index = 0, len(text) - 1
while left_index < right_index:
while left_index < right_index and not text[left_index].isalnum():
left_index += 1
while left_index < right_index and not text[right_index].isalnum():
right_index -= 1
if text[left_index].lower() != text[right_index].lower():
return False
left_index += 1
right_index -= 1
return True
This Python solution checks if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. The function checkPalindrome
processes the string by using two pointers:
- Initialize
left_index
at the start andright_index
at the end of the string. - Use a while loop to move
left_index
to the right until an alphanumeric character is found and similarly moveright_index
to the left. - Compare the characters at
left_index
andright_index
. If they are not the same, returnFalse
. - If the characters match, move both pointers closer to the center.
- Continue this process until the pointers meet or cross, at which point the function returns
True
, confirming the string is a palindrome.
Ensure proper functionality by testing with various inputs, including strings with special characters and mixed case letters. This method is efficient with a time complexity of O(n), where n is the length of the string, and it handles edge cases effectively.
No comments yet.