C# LeetCode 125: Valid Palindrome - (Easy)
Grant Riordan

Grant Riordan @grantdotdev

About: Lvl 12 Dev - Lead Software Engineer & Tech Author Twitter link below 👇

Location:
Yorkshire, England
Joined:
Jul 17, 2020

C# LeetCode 125: Valid Palindrome - (Easy)

Publish Date: Aug 6
0 0

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;
}
Enter fullscreen mode Exit fullscreen mode

Drop me a follow on twitter/x to hear about more articles in this series and other tech / developer tips.

Comments 0 total

    Add comment