Search code examples
c++recursion

I want my 2nd if-statement to do a recursion-type loop but it is not returning anything and defaulting to false, what am i doing wrong?


bool isPalindrome(string some_string) {
    if (some_string.length() == 0 || some_string.length() == 1) {
        return true;
    }

    if (some_string[0] == some_string[some_string.length() - 1]) {
        return isPalindrome(some_string.substr(1, some_string.length() - 1));
    }

    else {
        return false;
    }
}

First off, this code is to check if a string is palindrome or not. I looked up some links and thought I could use substr to get the characters after the first index and before the last character index, what am I doing wrong? This is my first time here so I'm sorry if this question was not well initiated.


Solution

  • The problem with your code is that substr() is being used in the wrong way. Here's a link to cppreference with full doc about this method. But in simple words, the problem is that the second argument of this method isn't the last index of the substring, but is the number of characters that should be included in the substring. So, in your second if, you call recursion with the same string, but without the first letter. So, for the string "abba", it will execute isPalindrome("bba") instead of isPalindrome("bb").

    To do what you intended to do, you have to change this line:

    return isPalindrome(some_string.substr(1, some_string.length() - 1));
    

    to this instead:

    return isPalindrome(some_string.substr(1, some_string.length() - 2));