Reverse Words in a String
Problem statement
Given a string s containing words and spaces, return the words in reverse order.
A word is a maximal sequence of non-space characters. The returned string must contain exactly one space between adjacent words and no leading or trailing spaces.
Function
reverseWords(s: String) → StringExamples
Example 1
s = "the sky is blue"return = "blue is sky the"The four words appear in the opposite order, separated by one space.
Example 2
s = " hello world "return = "world hello"Leading and trailing spaces are discarded before the two words are reversed.
Example 3
s = "a good example"return = "example good a"Multiple spaces between input words become a single space in the result.
Constraints
1 <= s.length <= 100000.scontains English letters, digits, punctuation, and space characters.scontains at least one word.