Problem
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:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Approach
Ok, so we know we need to remove all the spaces between the words, as we only care about the alphanumeric.
In my approach I decided to use LINQ - if you're not familiar with LINQ you can learn about it in my FreeCodeCamp article here.
I chose LINQ because it can be make the code more readable to achieve removal of spaces, and converting all letters to lowercase, in order to make the comparison easier.
We can then use 2 pointers to navigate from one side to another, and check the letters are the same from both ends, until they meet in the middle.
We can exit early as soon as we don't find a matching character, and if we make it all the way to the end of the loop, it means it's a palindrome.
Code
public bool IsPalindrome(string s)
{
var alphaNum = s
.Where(char.IsLetterOrDigit) //remove spaces
.Select(char.ToLower) // convert to lowercase
.ToArray(); // convert back to array
int left = 0, right = alphaNum.Length - 1;
while (left < right)
{
if (alphaNum[left] != alphaNum[right])
return false;
left++;
right--;
}
return true;
}
Drop me a follow on twitter/x to hear about more articles in this series and other tech / developer tips.
Top comments (0)