Description:
Given an input string str, return a string of the words in reverse order, concatenated by a single space, without extra spaces.
Example 1:
Input: "It is fun to learn DSA"
Output: "DSA learn to fun is It"
Example 2:
Input: "hello DSA"
Output: "DSA hello"
Example 3:
Input: " "
Output: ""
This problem is efficiently solved using basic string and array operations:
- Trim the input string to remove leading and trailing spaces.
- Split the string into an array of words using a regular expression that matches one or more spaces.
- Reverse the array of words.
- Join the reversed words with a single space.
- Return the result.
- Time Complexity: O(n), where n is the length of the string (for splitting, reversing, and joining).
- Space Complexity: O(n), for storing the array of words.