Skip to content

Commit 3b3bb26

Browse files
committed
feat: add reverse words in a string solution
1 parent 35d57d0 commit 3b3bb26

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Reverse Words In A String
2+
3+
## Description
4+
5+
Given an input string s, reverse the order of the words.
6+
7+
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
8+
9+
Return a string of the words in reverse order concatenated by a single space.
10+
11+
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.
12+
13+
**Example 1:**
14+
15+
```txt
16+
Input: s = "the sky is blue"
17+
Output: "blue is sky the"
18+
```
19+
20+
**Example 2:**
21+
22+
```txt
23+
Input: s = " hello world "
24+
Output: "world hello"
25+
```
26+
27+
Explanation: Your reversed string should not contain leading or trailing spaces.
28+
**Example 3:**
29+
30+
```txt
31+
Input: s = "a good example"
32+
Output: "example good a"
33+
```
34+
35+
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
36+
37+
Constraints:
38+
39+
- 1 <= s.length <= 104
40+
- s contains English letters (upper-case and lower-case), digits, and spaces ' '.
41+
- There is at least one word in s.
42+
43+
**Follow-up:** If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const reverseWords = (s) => s
2+
.trim()
3+
.replace(/\s+/g, ' ')
4+
.split(' ')
5+
.reverse()
6+
.join(' ');
7+
8+
module.exports = reverseWords;
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const reverseWords = require('./solution');
2+
3+
describe('Reverse Words In A String', () => {
4+
const testCases = [
5+
{
6+
input: 'the sky is blue',
7+
output: 'blue is sky the',
8+
},
9+
{
10+
input: ' hello world! ',
11+
output: 'world! hello',
12+
},
13+
{
14+
input: 'a good example',
15+
output: 'example good a',
16+
},
17+
{
18+
input: ' Bob Loves Alice ',
19+
output: 'Alice Loves Bob',
20+
},
21+
];
22+
23+
it('should return a string type', () => {
24+
const result = reverseWords('the sky is blue');
25+
expect(typeof result).toBe('string');
26+
});
27+
28+
it.each(testCases)('should return $output', (testCase) => {
29+
const result = reverseWords(testCase.input);
30+
expect(result).toBe(testCase.output);
31+
});
32+
});

0 commit comments

Comments
 (0)