Imagine you have a sentence, and your task is to keep every word the same, but flip the order they appear in. The last word should come first, and the first word should come last. This is a very common text problem, and solving it teaches you how to break a sentence into pieces and put it back together.
You are given a string s that contains some words. You must return a new string where the words appear in reverse order, with these rules:
Here is the tricky part: the input is messy. The words might be separated by one space or several spaces. There could also be spaces at the beginning or the end. Your job is to clean all of that up.
Input:
This is a string
Output:
string a is This
The four words are This, is, a, and string. We simply read them from last to first: string, then a, then is, then This. We join them with a single space, and that gives the answer.
A clear, beginner-friendly plan has two steps:
A simple way to handle spacing correctly: add the first word with no space, and for every word after it, add a space and then the word. This guarantees exactly one space between words and none at the ends.
The starter code gives you a function to complete:
using namespace std;
class Solution {
public:
string reverseWordOrder(string s) {
}
};
You receive the messy string s, and you return the cleaned, reversed string. The key insight is the same no matter the language: extract the words, then output them back-to-front, joined by single spaces.
This problem hides an important lesson: never trust input to be tidy. Real text is full of stray spaces. Good code separates the *meaningful* parts (the words) from the *noise* (the spaces) first, then does the actual work. Once your words are clean, reversing their order is easy.