2

I am trying to implement a function that will check to see if a word is a palindrome Below is the code that i have tried to use. the code works for one letter words obviously and words that don't start and end with the same letter. It fails on anything else. Please help

bool is_palindrome(int start, int end, const string & str)
{
    if (str[start] != str[end])
        return false;
    else if (start == end)
        return true;
    else
        return is_palindrome(start++, end--, str);

    return false;
}

here is the main function that tis function calls http://csel.cs.colorado.edu/%7Eekwhite/CSCI2270Fall2011/recursion_lab/palindrome.cxx

sarnold
  • 102,305
  • 22
  • 181
  • 238
Sean
  • 857
  • 1
  • 11
  • 21

5 Answers5

7

start++ increments the [local] variable start, and evaluates to the old value. You want to evaluate to the new value, and you don't need to alter the local variable at all.

So write start+1, end-1 instead, and then consider the case where your string has an even number of characters because there is another issue there.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

Couple of things:

Don't you need to use the prefix increment/decrement operators?

return is_palindrome(++start,--end, str);

Also, you need to make the test start >= end for it to work on an even number of characters.

0

It should be something like:

bool is_palindrome(int start, int end, const string& str)
{
        if (str[start] != str[end])
          return false;
        else if ((start == end) || (start < end))
          return true;
        else
          return is_palindrome(++start, --end, str);

        return false;
}
Randika Vishman
  • 7,983
  • 3
  • 57
  • 80
Suman
  • 1
0

Try this, not sure isit 100% working but for me it works:

bool is_palindrome(int start, int end, const string& str)
{
    if (str[start] != str[end])
      return false;
    else if (str[start] == str[end])
      {
        if (start <= end)
        return is_palindrome(start+1, end-1, str);
        return true;
      }

}
Newbie
  • 1
-1

recursively calls is palindrome function to check the string is palindrome or not. bool is_palindrome(int start, int end, const string& str) the start and end variables is used to contol the matching process for the palindrome. after each matching the next iteration is given using the recursion format