Reverse the order of words in a string while normalizing extra spaces.
Given a string s, reverse the order of the words.
A word is a maximal sequence of non-space characters. The returned string should contain the same words in reverse order, separated by exactly one space each, with no leading or trailing spaces.
This is a common string-processing problem that tests careful handling of whitespace and word boundaries.
Input Format
- A single string
s. smay contain letters, digits, punctuation, and spaces.- Words are separated by one or more spaces.
Output Format
- Return a new string containing the words of
sin reverse order. - Words must be separated by exactly one space.
- No leading or trailing spaces should appear in the result.
Constraints
- 1 <=
s.length<= scontains printable characters and spaces.- The result must preserve each word exactly as written, only changing word order.
Example 1
Input
s = "the sky is blue"
Output
"blue is sky the"
Explanation
The words are the, sky, is, and blue. Reversing their order gives blue is sky the.
Example 2
Input
s = " hello world "
Output
"world hello"
Explanation
Extra spaces are removed, and the two words are reversed.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.