A man, a plan, a canal. Panama!

<update> I didn't realize that my “for“ loop was garbled by .Text: line 20 should read as for (int i=0;i<halfwayMark;i++) < /update>

The folks over at channel9 recently did a whiteboard session (simulating an interview technique used at Microsoft to screen candidates) whereby the “candidate” was asked to whiteboard an algorithm to determine if a string was a palindrome. While I don't know C/C++, I decided to give it a shot in managed code (C# in this case). I also wanted to take a different approach rather than dealing with traversing the string with multiple loops. Here is what I hacked together:

1static private bool isPalindrome (string stringToTest)

2{

3 char[] stringChars = stringToTest.ToCharArray();

4

5 // format the string

6 foreach (char character in stringChars)

7 {

8 if (char.IsPunctuation(character) || char.IsSeparator(character))

9   {
    10     stringToTest = stringToTest.Replace(character.ToString(), "").ToLower();
    11   }
12 }

13

14 int halfwayMark = (stringToTest.Length/2);
15 char[] firstHalf = stringToTest.Substring(0, halfwayMark).ToCharArray();
16 char[] secondHalf = stringToTest.Substring(halfwayMark).ToCharArray();

17

18 Array.Reverse(secondHalf);

19

20 for (int i=0;i

21 {

22 if (firstHalf[i] != secondHalf[i])

23   {
    24     return false;
    25   }
26 }
27 return true;
28}

This works on strings with an even or odd number of characters. Managed code makes it so much easier/cleaner than C/C++ IMO. But maybe that's just me :-)

No comments yet