Is string same as its reversed string(i.e Is it a Palindrome)

Lately I have been reading up on interview related questions. One of the favorite interview questions interviewers have is to “write a program to check if a string is the same as its reversed string i.e check that a string is a Palindrone”. To make it more interesting, they ask to not use Array.Reverse.

Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void IsStringSameAsItsReversedStringThatIsItIsAPalinDrome()
        {
            var result=new StringHelper().IsStringSameAsItsReversedStringThatIsItIsAPalinDrome("Anna");
            Assert.AreEqual(result, true);
        }
    }

    public class StringHelper
    {
         public bool IsStringSameAsItsReversedStringThatIsItIsAPalinDrome(string tempString)
        {
            if(String.IsNullOrEmpty(tempString))
            {
                throw new ArgumentException();
            }
            var tempStringLower= tempString.ToLower();
            var tempArray= tempStringLower.ToCharArray();
            var tempArray1 = Reverse(tempArray);
            var reversedString=new string(tempArray1);
            if (reversedString.Equals(tempStringLower))
                return true;
            return false;
        }
        //This function just reverses a array of characters.
        private char[] Reverse(char[] characters)
        {
            for(int counter=0; counter<characters.Length/2;counter++)
            {
                char character = characters[counter];
                characters[counter] = characters[characters.Length - counter -1];
                characters[characters.Length - counter - 1] = character;
            }
            return characters;
        }
    }
}

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.