Skip to content

Commit 7ea002f

Browse files
committed
add: Reverse Words in a String
1 parent e45d586 commit 7ea002f

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ This is the solutions collection of my LeetCode submissions, most of them are pr
4242
|130|[Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) | [JavaScript](./src/surrounded-regions/res.js)|Medium|
4343
|133|[Clone Graph](https://leetcode.com/problems/clone-graph/) | [JavaScript](./src/clone-graph/res.js)|Medium|
4444
|136|[Single Number](https://leetcode.com/problems/single-number/) | [JavaScript](./src/single-number/res.js)|Easy|
45+
46+
|151|[Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [JavaScript](./src/reverse-words-in-a-string/res.js)|Medium|
4547
|152|[Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | [JavaScript](./src/maximum-product-subarray/res.js)|Medium|
4648
|175|[Combine Two Tables](https://leetcode.com/problems/combine-two-tables/)| [SQL](./src/combine-two-tables/res.txt)|Easy|
4749
|176|[Second Highest Salary](https://leetcode.com/problems/second-highest-salary/)| [SQL](./src/second-highest-salary/res.txt)|Easy|

src/reverse-words-in-a-string/res.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* res.js
3+
* @authors Joe Jiang (hijiangtao@gmail.com)
4+
* @date 2017-05-11 11:57:43
5+
*
6+
* @param {string} str
7+
* @returns {string}
8+
*/
9+
let reverseWords = function(str) {
10+
let len = str.length,
11+
res = '',
12+
begin = 0;
13+
14+
// 处理字符串为全空的情况
15+
while (begin < len && str.charAt(begin) === ' ') begin++;
16+
if (begin === len) return res;
17+
18+
for (let i = begin; i < len;) {
19+
let space = '',
20+
end = begin,
21+
tmpstr = '';
22+
23+
while (i < len && str.charAt(i) !== ' ') {
24+
tmpstr += str.charAt(i);
25+
i++;
26+
}
27+
while (i < len && str.charAt(i) === ' ') i++;
28+
29+
if (i < len) space = ' ';
30+
31+
res = space + tmpstr + res;
32+
}
33+
34+
return res;
35+
};

0 commit comments

Comments
 (0)