Let a string representing a sentence. A sentence is composed of words separated by a space.
For example: "Welcome to Algo Planet" is a sentence. To make easier, we do not consider
cases where words are separated by several spaces.
The goal is to find a solution in-place which reverses the sentence word by word.
With our previous example, the solution must return "Planet Algo to Welcome".
Take a paper and a pen anf find the solution !
Reasonning step
The solution is not so complicated but needs two steps. The idea is first
to reverse the whole sentence:
"tenalP oglA ot emocleW"
Once done, the next step is to reverse each word:
"Planet Algo to Welcome"
The first step is relatively easy since we just have to swap the characters using
two local variables starting respectively at the beginning and the end of the string:
void reverseSentence(string &s)
{
int lower = 0;
int upper = s.size()-1;
while(lower < upper)
{
auto tmp = s[upper];
s[upper] = s[lower];
s[lower] = tmp;
upper--;
lower++;
}
}
The second step is to reverse the words in the reversed sentence. To do that, it is necessary
to determine when a word starts and when it ends. The end is detected by the next space. Once
the bounds determined we can do the same process we did to reverse the whole sentence: