Description
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.
Return a string of the words in reverse order concatenated by a single space.
Note that s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Key Requirements
- Remove extra spaces between words and at the beginning/end of the string.
- Reverse the order of words (not characters).
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
✔️ My Submission
var reverseWords = function(s) {
return s.replace(/\s+/g, " ").trim().split(' ').reverse().join(' ');
};
- Removed all extra spaces from
s
using the regular expression/\s+/g
with thereplace
method. - However, this alone did not remove the leading and trailing spaces, so I added the
trim
method to eliminate them. - Next, I used
split(' ')
to break the string into an array of words. - Since it’s now an array, I applied the reverse method to rearrange the words in
reverse
order. - Finally, I used the
join(' ')
method to convert the array back into a string.
Top comments (2)
A version without
regex
(I'm not a big fan):Thanks for sharing ! This is c# version
public string ReverseWords(string s) {
return string.Join(" ", s.Split(' ', StringSplitOptions.RemoveEmptyEntries).Reverse());
}