tags:

views:

115

answers:

1

I want to write a method to determine if a given string is a palindrome. E.g. "Madam I'm Adam", or "A man, a plan, a canal, Panama".

The prototype for the function is:

bool is_palindrome(char const * str)

I have a simple logic to check for equality by moving forward & backward from extreme ends of the string. But, i would like to know how many efficient ways to do this ? All ideas welcome from C++ gurus..

+1  A: 

I don't think there is a much more efficient way, you do have to compare every character in the string.

Possible optimisations: You only have to check the first half of the string, and you can break out early as soon as you find a mismatch.

bool is_palindrome(char const * str) 
{
    size_t len = strlen(str);
    bool isPalindrome = false;    // It's debatable if a blank string is a palindrome or not

    for(int i = 0; i < len / 2; i++)
    {
        if(str[i] != str[len - i - 1])
        {
            isPalindrome = false;
            break;
        }
        isPalindrome = true;
    }

    return isPalindrome;
}
DanDan
Compiled code might be tighter if the source code used two pointers instead of an array indexer; e.g. `if (*startPtr++ != *endPtr--) {...}`
ChrisW