DEV Community

jihyun-j
jihyun-j

Posted on

1

[Algorithm] 151. Reverse Words in a String

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"
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: s = "  hello world  "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode

✔️ My Submission

var reverseWords = function(s) {
    return s.replace(/\s+/g, " ").trim().split(' ').reverse().join(' ');
};
Enter fullscreen mode Exit fullscreen mode
  1. Removed all extra spaces from s using the regular expression /\s+/g with the replace method.
  2. However, this alone did not remove the leading and trailing spaces, so I added the trim method to eliminate them.
  3. Next, I used split(' ') to break the string into an array of words.
  4. Since it’s now an array, I applied the reverse method to rearrange the words in reverse order.
  5. Finally, I used the join(' ') method to convert the array back into a string.
Retry later

Top comments (2)

Collapse
 
alexmustiere profile image
Alex Mustiere

A version without regex(I'm not a big fan):

const reverseWords = (s) => s.split(' ').filter((c) => c !== '').reverse().join(' ');
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stevsharp profile image
Spyros Ponaris • Edited

Thanks for sharing ! This is c# version

public string ReverseWords(string s) {
return string.Join(" ", s.Split(' ', StringSplitOptions.RemoveEmptyEntries).Reverse());
}

Retry later
Retry later