Tuesday, June 2, 2015

Palindrome (C#) : Algorithm

Write a function that checks if a given sentence is a palindrome. A palindrome is a word, phrase, verse, or sentence that reads the same backward or forward. Only the order of English alphabet letters (A-Z and a-z) should be considered, other characters should be ignored.

For example, IsPalindrome("Noel sees Leon.") should return true as spaces, period, and case should be ignored resulting with "noelseesleon" which is a palindrome since it reads same backward and forward.

Code Snippet
  1. using System;
  2. using System.Linq;
  3. using System.Text.RegularExpressions;
  4. public class Palindrome
  5. {
  6.     public static bool IsPalindrome(string str)
  7.     {
  8.         string tmpStr = str.ToLower().Trim();
  9.         tmpStr = Regex.Replace(tmpStr, @"[^a-zA-Z]+", "");  //Replace all the special characters
  10.         return tmpStr.SequenceEqual(tmpStr.Reverse());
  11.     }
  12.  
  13.     public static void Main(string[] args)
  14.     {
  15.  
  16.         Console.WriteLine(IsPalindrome("Noel sees Leon."));
  17.     }
  18. }

No comments: