+ 2
Interview: Reverse string using recursion (substring)
Studying for some interview questions and I'm trying to learn reverse a string in different way. For this code, I wanted to do it using recursion, I was stuck so I looked online for help and found that substrings work for this. HOWEVER, now I'm stuck trying to understand how this substring reversed the string! Can someone help me understand this? #include <iostream> #include <string> using namespace std; void reverseString(string s); void reverseString(string str) { //exit once string is empty if (str.size() == 0) return; //??substring magic?? reverseString(str.substr(1)); cout << str[0]; } int main() { string str = "hello there"; reverseString(str); return 0; }
1 Respuesta
+ 4
Just go through it step by step to see what happens.
Imagine a call like reverseString("hi"):
- reverseString("i");
- reverseString(""); //this returns
- //then i will get printed, because of the call to reverseString("i")
- then "h" will get printed. Because it is the first letter in the: reverseString("hi") call
Really go through it step by step, unwrap the calls on paper manually, that will help you understand what is happening.
so lets unwrap the calls for "hello there":
- "hello there"
- "ello there"
- "llo there"
- "lo there"
- "o there"
....
- "" -> returns
- "e" -> prints 'e'
- "re" -> prints 'r'
...
- "o there" -> prints 'o'
- "lo there" -> prints 'l'
- "llo there" -> prints 'l'
- "ello there" -> prints 'e'
- "hello there" -> prints 'h'
So the output in sum would be:
> ereht olleh
(As a side note ofc. in reality you would just:
auto reversed{ std::string(str.rbegin(), str.rend()) };
std::cout << reversed;
)