This problem asks you to take a sentence and flip the letters inside every word — but keep the words sitting in the same places they started.
Imagine the sentence is a row of small boxes, and each box holds one word. The order of the boxes never changes. You only spin the letters *inside* each box around so they read backward.
So This becomes sihT, and string becomes gnirts. But the first word is still first, and the last word is still last.
A quick rule of thumb: the words stay put, only their spelling gets reversed.
Real sentences are messy. The problem warns you about two things:
You are not allowed to clean any of this up. Every space, even a run of several spaces in a row, must appear in the output in the exact same place. Think of spaces as walls between words. You reverse the letters between the walls, but you never move, add, or remove a wall.
Example 1
Input: This is a string
Output: sihT si a gnirts
Look at each word on its own:
This → sihTis → sia → a (a single letter reversed is still itself)string → gnirtsThe four words are still in the same order. Only the letters flipped.
Example 2
Input: I love coding
Output: I evol gnidoc
I → Ilove → evolcoding → gnidocA simple plan in plain steps:
You are given this starting point to fill in:
using namespace std;
class Solution {
public:
string reverseWords(string s) {
}
};
The key idea to hold onto: treat each word as its own little block, reverse the letters inside that block, and never touch the spaces.