56.3k views
2 votes
Give a recursive algorithm that takes as input a string s, removes the blank characters and reverses the string. For example, on input "Hello There", the algorithm should return "erehTolleH". The function IsBlank(c) returns a boolean value indicating whether the character c is the blank character. Your algorithm should not use a loop.

1 Answer

0 votes

Answer:

#include <iostream>

using namespace std;

void recReverse(string exp)

{

if (exp.size() == 0) //check for empty string

{

return;

}

if (exp[0] == ' ')

{

recReverse(exp.substr(1)); //only subtracting, not printing the spaces

}

else

{

recReverse(exp.substr(1)); //subtracting the previously first element

cout << exp[0]; //printing new first element

}

}

int main()

{

string exp = "Hello There";

recReverse(exp);

return 0;

}

Step-by-step explanation:

A recursive function calls itself and works kind of like a loop. A russian doll, if you will. The downside of this program is that if the statement becomes too long it becomes very slow. The upside is, that i some cases, it provides elegant solutions.

In the above code, we have first made sure that we don't have a blank string input. In case we do, we've made sure the function exits before doing any extra work. Then if the next element of the string is a space, we haven't printed it. Instead we've omitted the 'cout' and carried on with our recursion. Finally, in the else statement, we are printing the character along with subtracting it. Giving us our final recursive call backwards printing.

User Hmghaly
by
5.1k points