forked from ManishGupta1908/LeetCode-with-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathres.js
35 lines (29 loc) · 760 Bytes
/
res.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* res.js
* @authors Joe Jiang (hijiangtao@gmail.com)
* @date 2017-05-11 11:57:43
*
* @param {string} str
* @returns {string}
*/
let reverseWords = function(str) {
let len = str.length,
res = '',
begin = 0;
// 处理字符串为全空的情况
while (begin < len && str.charAt(begin) === ' ') begin++;
if (begin === len) return res;
for (let i = begin; i < len;) {
let space = '',
end = begin,
tmpstr = '';
while (i < len && str.charAt(i) !== ' ') {
tmpstr += str.charAt(i);
i++;
}
while (i < len && str.charAt(i) === ' ') i++;
if (i < len) space = ' ';
res = space + tmpstr + res;
}
return res;
};