Valid Palindrome
String, Two Pointers
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s
, return true
if it is a palindrome, or false
otherwise.
Example 1:
Example 2:
Example 3:
Constraints:
The input string
s
consists only of printable ASCII characters.The string
s
can be empty.The string
s
can contain spaces, punctuation, and other non-alphanumeric characters.The string
s
can contain both uppercase and lowercase letters.
Questions to Clarify:
Case Sensitivity: Should the palindrome check be case-sensitive or case-insensitive? The problem statement suggests it should be case-insensitive, but it would be good to confirm this.
Non-Alphanumeric Characters: Should non-alphanumeric characters be ignored when checking for a palindrome? The problem statement suggests they should be, but again, it would be good to confirm this.
Null Input: How should the function handle a null input? Should it return
true
(since a null string can be considered a special case of an empty string),false
, or should it throw an exception?Large Inputs: What is the maximum length of the input string
s
? This could affect the choice of algorithm, especially for very long strings.Performance Requirements: Are there any performance requirements or constraints? For example, does the function need to run in a certain amount of time or use a certain amount of memory?
Solutions
Please note that this function considers an empty string and a null string as palindromes, which is consistent with the definition of a palindrome. An empty string reads the same forward and backward, and a null string can be considered a special case of an empty string. However, some people might argue that a null string should not be considered a palindrome, so you might want to handle this case differently depending on your specific requirements.
Approach – Brute Force Technique
The code first converts the string to lowercase and filters out non-alphanumeric characters. It then checks each character from the start of the string to the middle against the corresponding character from the end. If it finds a pair of characters that don’t match, it immediately returns false
. If it doesn’t find any mismatched pairs, it returns true
after checking all pairs.
Steps
Check if the string is not null: The
if (s is not null)
statement checks if the input strings
is not null. Ifs
is null, the function will skip the rest of the code and returntrue
.Convert to lowercase and filter out non-alphanumeric characters: The
Span<char> str = s.ToLower().Where(c => char.IsLetterOrDigit(c)).ToArray();
statement does three things:s.ToLower()
converts all characters in the strings
to lowercase.Where(c => char.IsLetterOrDigit(c))
filters out any characters that are not letters or digits.ToArray()
converts the result back into an array of characters.
Check each character pair: The
for (int i = 0; i < len / 2; i++)
loop iterates over each character in the first half of the stringstr
. For each character, it checks if it is the same as the corresponding character from the end of the string. If the characters are not the same, the function immediately returnsfalse
.Return true if no mismatches are found: If the function has checked all character pairs and hasn't found any mismatches, it returns
true
.
Complexity
Time complexity:
O(N)
Space complexity:
O(N)
Approach – Two Pointers Technique
Two pointers to compare characters without creating a new string.
Steps
Initialize two pointers: The
int i = 0, j = s.Length - 1;
line initializes two pointers,i
andj
.i
starts at the beginning of the strings
andj
starts at the end.Start of the loop: The
while (i < j)
line starts a loop that continues as long asi
is less thanj
. This means the loop will continue until the two pointers meet or cross each other.Skip non-alphanumeric characters from the start: The
while (i < j && !Char.IsLetterOrDigit(s[i])) i++;
line inside the loop skips any non-alphanumeric characters from the start of the string. It does this by checking if the character at thei
th position is a letter or digit, and if it's not, it incrementsi
to move to the next character.Skip non-alphanumeric characters from the end: The
while (i < j && !Char.IsLetterOrDigit(s[j])) j--;
line inside the loop skips any non-alphanumeric characters from the end of the string. It does this by checking if the character at thej
th position is a letter or digit, and if it's not, it decrementsj
to move to the previous character.Compare characters: The
if (Char.ToLower(s[i]) != Char.ToLower(s[j])) return false;
line inside the loop compares the characters at thei
th andj
th positions. If they are not the same, it returnsfalse
, indicating the string is not a palindrome.Move the pointers: The
i++; j--;
lines inside the loop move the pointers towards each other. This prepares for the next iteration of the loop, where the next pair of characters will be compared.Return true: The
return true;
line after the loop returnstrue
, indicating the string is a palindrome. This line is only reached if all pairs of characters have been compared and no mismatches have been found.
Complexity
Time complexity:
O(N)
Space complexity:
O(1)
Last updated