Skip to content

Commit 129b2b8

Browse files
author
Tushar Borole
committed
151. Reverse Words in a String
1 parent 2b4919a commit 129b2b8

File tree

3 files changed

+92
-82
lines changed

3 files changed

+92
-82
lines changed

.idea/workspace.xml

Lines changed: 42 additions & 82 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
| 46 | [Permutations](https://leetcode.com/problems/permutations/) | [permutations.js](permutations.js) | 88 ms | 37.6 MB | Medium |
7171
| 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) | [remove_duplicates_from_sorted_array_II.js](remove_duplicates_from_sorted_array_II.js) | 64 ms | 35.8 MB | Medium |
7272
| 78 | [Subsets](https://leetcode.com/problems/subsets/) | [subset.js](subset.js) | 60 ms | 35 MB | Medium |
73+
| 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [reverse_words_in_string.js](reverse_words_in_string.js) | 56 ms | 34.6 MB | Medium |
7374

7475

7576
## Others

reverse_words_in_string.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Given an input string, reverse the string word by word.
2+
//
3+
//
4+
//
5+
// Example 1:
6+
//
7+
// Input: "the sky is blue"
8+
// Output: "blue is sky the"
9+
// Example 2:
10+
//
11+
// Input: " hello world! "
12+
// Output: "world! hello"
13+
// Explanation: Your reversed string should not contain leading or trailing spaces.
14+
// Example 3:
15+
//
16+
// Input: "a good example"
17+
// Output: "example good a"
18+
// Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
19+
//
20+
//
21+
// Note:
22+
//
23+
// A word is defined as a sequence of non-space characters.
24+
// Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
25+
// You need to reduce multiple spaces between two words to a single space in the reversed string.
26+
//
27+
//
28+
// Follow up:
29+
//
30+
// For C programmers, try to solve it in-place in O(1) extra space.
31+
32+
/**
33+
* @param {string} s
34+
* @return {string}
35+
*/
36+
var reverseWords = function(s) {
37+
let stringArray = s
38+
.trim()
39+
.split(" ")
40+
.filter(a => a.length > 0);
41+
let out = "";
42+
for (let i = stringArray.length - 1; i >= 0; i--) {
43+
out += stringArray[i] + (i >= 1 ? " " : "");
44+
}
45+
46+
return out;
47+
};
48+
49+
reverseWords("a good example"); //?

0 commit comments

Comments
 (0)