Skip to content

Instantly share code, notes, and snippets.

@ManojLingala
Last active May 8, 2024 10:24
Show Gist options
  • Save ManojLingala/ccb51dc8a9fd46fe603fbbdfcf8f3475 to your computer and use it in GitHub Desktop.
Save ManojLingala/ccb51dc8a9fd46fe603fbbdfcf8f3475 to your computer and use it in GitHub Desktop.
Palindrome
Create a New .NET 6.0 Console Application
```dotnet new console -n PalindromeCheckerApp```
Change directory to the newly created project
```cd PalindromeCheckerApp ```
Copy this program.cs
using Palindrome;
public class Program
{
public static void Main()
{
PalindromeChecker.Check("abcba", true);
PalindromeChecker.Check("abcde", false);
PalindromeChecker.Check("Mr owl ate my metal worm", true);
PalindromeChecker.Check("Never Odd Or Even", true);
PalindromeChecker.Check("Never Even Or Odd", false);
}
}
Create a new file and name it PalindromeChecker and copy the below code in the file
using System.Text.RegularExpressions;
namespace Palindrome;
public class PalindromeChecker
{
private static bool IsPalindrome(string s)
{
try
{
// filters out non-alphanumeric characters and convert to lowercase
var cleanedString = Regex.Replace(s, @"[^a-zA-Z0-9]", "").ToLower();
return IsPalindromeRecursive(cleanedString, 0, cleanedString.Length - 1);
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
return false;
}
}
//helper method for recursive check
private static bool IsPalindromeRecursive(string s, int left, int right)
{
// Base case: When pointers have crossed or are at the same position
if (left >= right)
return true;
// Recursive case: Compare characters and recurse
return s[left] == s[right] && IsPalindromeRecursive(s, left + 1, right - 1);
}
public static void Check(string s, bool shouldBePalindrome)
{
try
{
Console.WriteLine(IsPalindrome(s) == shouldBePalindrome ? "pass" : "FAIL");
}
catch (Exception ex)
{
Console.WriteLine($"Test failed due to an error: {ex.Message}");
}
}
}
Build and Run the Application
```
dotnet run
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment