678. Reversing the Letters Inside Each Word
A line of text is given, with words separated by single spaces. Reverse the characters WITHIN each word, leaving the words themselves in their original order and the spacing unchanged.
abc def -> cba fed
one two three -> eno owt eerht
Let's take LeetCode contest -> s'teL ekat edoCteeL tsetnoc
## The opposite of problem 621
621 reverses the ORDER of the words and leaves each word's letters alone. This reverses each word's letters and leaves the order alone.
Together they are the two halves of "reverse the whole line": reversing everything is the same as doing both, in either order. That is a pleasant check to know, and it is the reason these two problems sit together.
## Find each word, then reverse it in place
i = 0
while i < n:
if s[i] is a space: i += 1; continue
j = i
while j < n and s[j] is not a space: j += 1
reverse s[i .. j-1]
i = j
The outer scan is the run-finding sweep from problem 623, and the inner reversal is the converging swap from problem 625. Neither is new; the problem is assembling them.
## The reversal bounds
The word runs from i to j - 1, because j stopped ON the space or past the end. Reversing
i .. j instead would drag the separator into the word.
That off-by-one is invisible on a single-word line, which is why the tests include several words.
## Spacing is preserved exactly
Nothing about the separators changes, so a line with unusual spacing keeps it. This is why the problem can afford to say nothing about collapsing spaces, unlike 621 and 674 where the output spacing is part of the question.
## Reading the input
The line contains spaces, so read it WHOLE. Splitting on whitespace and rejoining would work here only because the constraints promise single spaces, and would silently change a line with doubled ones.
## Cost
Time O(n). Space O(n) for the output, or O(1) editing the buffer in place.
Constraints - `1 ≤ length of the line ≤ 200000` - words are separated by single spaces with none at either end - characters are printable ASCII other than tab
Input
One line of text. Words are separated by single spaces, and the line has no leading or trailing space.
Output
Print the line with the characters of each word reversed.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.