Given a character array s, reverse the order of the words.
A word is a sequence of non-space characters. The words in s are separated by a single space.
Rearrange the characters of s in place and return the resulting array.
Function Signature
def reverse_words(s: list[str]) -> list[str]:
Rules
-
s
is a Python list where each element is a single-character string, for example
["t","h","e"]
.
-
Modify
s
in place and return the same list. The result must contain the words of the input in reverse order, each spelled as it was, with one space between adjacent words.
Constraints
-
1 <= len(s) <= 10^5
-
s[i]
is an English letter (uppercase or lowercase), a digit, or a space
' '
.
-
There is at least one word in
s
.
-
s
has no leading or trailing spaces.
-
All words in
s
are separated by a single space.
Examples
Input: s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
The words "the", "sky", "is", "blue" come out as "blue", "is", "sky", "the", and each word keeps its spelling.
Input: s = ["a"]
Output: ["a"]
A single word has nothing to swap places with, so the array is unchanged.
Input: s = ["a"," ","b","c"]
Output: ["b","c"," ","a"]
The two words "a" and "bc" trade places. The space moves from index 1 to index 2 because the first word is now two characters long.