08 April 2011

C++ Proficiency - Palindromes

Write a boolean in C++ to detect if a string is a palindrome.
This was a question asked in a M_______t technical interview. For the life of me, I couldn't recall what a palindrome even was at that time. The example given was level.   1:  bool isPalindrome(string test) { 2:   3:   for (int i=0; i < test.length() - 1;i++){ 4:   if (test[i] != test[test.length() - 1 - i]) return false; 5:   } 6:   7:   return true; 8:  }
Around line 2 one would want to add some replace functions to remove non-alpha characters and spaces. Think about the common example used "dammit i'm mad". It will return false if given to this function as is but is truly a palindrome.

I think a better bool function would be to detect if a string is a Palinism. In other words, if the coherency of the sentences are random babble, mixed with n number of keywords, add in some further nonsense, it returns true.

0 comments: