Why it works
- Reading from the end, the first word found is the last word of the string. So the words come out already in the order the answer needs, and nothing has to be reversed afterwards.
- Spaces never go into the answer: end steps over them, and only whole words are taken. The single spaces come from joining the words, so extra spaces at the start, at the end and between the words disappear by themselves.
- After a word, end jumps straight to the left of it, so no character is read twice.
Complexity
Time O(n): both pointers only move left, end passes the spaces and start the letters, so each character is passed once. Memory O(n): the list of words and the answer hold up to n characters.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗