...

/

Solution Review 2: Is this String a Palindrome?

Solution Review 2: Is this String a Palindrome?

This lesson provides a detailed review of the solution to the challenge in the previous lesson

Solution: Palindrome or not?

Press + to interact
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string text) {
if (text.size() <= 1) {
return true;
}
else {
if (text[0] == text[text.size()-1]) {
return isPalindrome(text.substr(1, text.size()-2));
}
}
return false;
}
int main() {
string input1 = "toot";
string input2 = "dadad";
bool answer1 = isPalindrome(input1);
bool answer2 = isPalindrome(input2);
cout << "Is " << input1 << " a Palindrome? = " << answer1 << endl;
cout << "Is " << input2 << " a Palindrome? = " << answer2 << endl;
}

Understanding the Code

Every recursive code has two functions; the recursive function and the main function.

Driver Function

The recursive function is called within the driver function so lets first look at what it does, from line 17 to 28.

  • In this driver method we have an array of strings which has two palindrome and one non-palindrome text string.

  • For each value, it calls on the isPalindrome method and the output of the function is stored in an answer variable.

  • This is checked in an if-condition. Given ...