C# - Palindrome

13. July 2011 18:00


Another common interview question is to write a function to detect if a string is a palindrome. For thoose who are not aware a palindrome is the same word spelt backwards as forwards eg "RACECAR".


Places tend to ask this because it can be solved in multiple ways. The two main methods are either using a for loop or using recursion. I don't think the recusion method is an advantage in c# because of the lack of pointers. So that method is going to be skipped here. The reason why they ask this is because it has a nice catch on how the issue of how to deal with an odd number of letters. This is actually very simple since the odd letter is in the middle it will be compared to its self. So there is never any need to compare the middle letter. An example is "RAC" "E" "CAR".


Here is a solution that will work for both even and odd cases ..


public static bool IsPalindrome(string str)
    for (int i = 0; i < str.Length / 2; i++)
        if (str[i] != str[str.Length - (i + 1)])
            return false;
    return true;


Something that is intresting is that as well as a simple technical test the interviewer can challange on the functionality of the operation of the odd case. Sometimes they do this to see if the person is going to defend them self or just role over and show a lack of confidence in their solution.

E-mail Kick it! DZone it! del.icio.us Permalink