Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Your reversed string should not contain leading or trailing spaces, and words should be separated by a single space.
-
Constraints:
1 <= s.length <= 10^4scontains English letters (upper-lower case), digits, and spaces' '.- There is at least one word in
s.
-
Example 1:
- Input:
s = "the sky is blue" - Output:
"blue is sky the"
- Input:
-
Example 2:
- Input:
s = " hello world " - Output:
"world hello" - Explanation: Your reversed string should not contain leading or trailing spaces.
- Input:
-
Example 3:
- Input:
s = "a good example" - Output:
"example good a" - Explanation: Reduce multiple spaces between two words to a single space.
- Input:
Solution
The problem asks us to reverse the order of words in a string, while also cleaning up extra spaces. This can be broken down into a few distinct steps:
- Split the string into words: Identify individual words. Many languages have built-in
split()functions that can handle multiple spaces between words and automatically remove leading/trailing spaces if used correctly (e.g., by splitting on one or more spaces). - Reverse the order of words: Once you have an array or list of words, reverse its order.
- Join the words back into a string: Combine the reversed list of words into a single string, using exactly one space as a separator between words.
Detailed Steps:
- Trim and Split: Use a method that effectively splits the string by spaces, treating multiple spaces as a single delimiter and ignoring leading/trailing spaces. In Python,
s.split()without arguments does exactly this. - Reverse List: Reverse the order of the list of words obtained in the previous step.
- Join with Single Space: Concatenate the words back together, inserting a single space character between each word.
class Solution:
def reverseWords(self, s: str) -> str:
# Step 1: Split the string by one or more spaces.
# s.split() without arguments automatically handles multiple
# spaces and leading/trailing spaces by splitting on any whitespace
# and discarding empty strings that result.
words = s.split()
# Step 2: Reverse the list of words.
words.reverse()
# Step 3: Join the words back with a single space.
return " ".join(words)