52. Flip the Phrase
A noticeboard prints messages one word at a time, and the editor wants to show each message with its words in reverse order. You are given a string s made of words separated by spaces. A word is a run of letters and digits. The string may have extra spaces at the start, at the end, or several spaces in a row between words.
Return a new string containing the same words in reverse order, separated by exactly one space, with no leading or trailing space. The characters inside each word keep their original order. The input always contains at least one word.
Example 1
- Input:
- s = " quick brown fox "
- Output:
- "fox brown quick"
- Explanation:
The words are quick, brown and fox; reversed and joined with single spaces this gives fox brown quick.
Example 2
- Input:
- s = "solo"
- Output:
- "solo"
- Explanation:
A single word stays as it is.
Constraints
1 ≤ s.length ≤ 105
s contains letters, digits and the space character, and at least one word
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)