Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. Words in s will be separated by at least one space. The reversed string should not contain leading or trailing spaces. Multiple spaces between two words should be reduced to a single space in the reversed string.
Constraints:
1 <= s.length <= 10^4sconsists of English letters (lower-case and upper-case), digits, and spaces.scontains at least one word.
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
- Example 2:
Input: s = " hello world "
Output: "world hello"
Solution
The most straightforward approach involves standard string manipulation functions available in most programming languages.
- High-Level Steps:
- Clean up spaces: Remove any leading or trailing spaces from the input string. Many languages have a
trim()method for this, or their split functions handle it implicitly. - Split into words: Divide the cleaned string into individual words using a space as the delimiter. Be careful to handle cases with multiple spaces between words, which might result in empty strings if not processed correctly (e.g., using a regex split or filtering empty strings after a simple split).
- Reverse word order: Reverse the list or array of words.
- Join words: Combine the reversed words back into a single string, using a single space as the separator between them.
- Clean up spaces: Remove any leading or trailing spaces from the input string. Many languages have a
class Solution:
def reverseWords(self, s: str) -> str:
# Step 1 & 2: Clean up spaces and split into words
# The split() method in Python without arguments handles multiple spaces
# and leading/trailing spaces by default, treating any sequence of
# whitespace as a single delimiter and not returning empty strings.
words = s.split()
# Step 3: Reverse the order of words
words.reverse() # In-place reversal of the list
# Step 4: Join the words back with a single space
return " ".join(words)
# Example Usage:
# sol = Solution()
# print(sol.reverseWords("the sky is blue")) # Output: "blue is sky the"
# print(sol.reverseWords(" hello world ")) # Output: "world hello"
# print(sol.reverseWords("a good example")) # Output: "example good a"
