[Algorithm] 151. Reverse Words in a String

[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"

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(' ');
};
  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.
Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
“unlocking-llms:-innovative-strategies-for-game-and-model-optimization”

“Unlocking LLMs: Innovative Strategies for Game and Model Optimization”

Next Post
how-to-get-alignment-from-the-board-with-your-ai-strategy-—-karen-stroup,-chief-digital-officer,-wex

How to get alignment from the board with your AI strategy — Karen Stroup, Chief Digital Officer, WEX

Related Posts