反转字符串中的单词 III
给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入:s = "Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"
1
2
2
/**
* @param {string} s
* @return {string}
*/
var reverseWords = function(s) {
const ret = [];
const length = s.length;
let i = 0;
while (i < length) {
let start = i;
while (i < length && s.charAt(i) != ' ') {
i++;
}
for (let p = start; p < i; p++) {
ret.push(s.charAt(start + i - 1 - p));
}
while (i < length && s.charAt(i) == ' ') {
i++;
ret.push(' ');
}
}
return ret.join('');
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii