Reverse Words in a String
Difficulty: Easy · Topics: String, Array, Basics
Difficulty: Easy | Tags: String, Array, Basics
Description
Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. Return the string with words in reverse order, separated by a single space. Remove any leading/trailing/extra spaces.
Implement:
reverseWords(s) → String
Examples
Example 1:
Input: "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: " hello world "
Output: "world hello"
Example 3:
Input: "a"
Output: "a"
Example 4:
Input: " Bob Loves Alice "
Output: "Alice Loves Bob"
Constraints
1 <= s.length <= 10^4scontains English letters, digits, and spaces.- There is at least one word in
s.
Hints
Hint 1
Split on whitespace, filter empty strings, then reverse the list and join.