反转句子形式的字符串
- Runtime: 84 ms, faster than 81.42%
- Memory Usage: 45.7 MB, less than 20.66%
- 时间复杂度O(n),空间复杂度O(n)
/**
* @param {string} s
* @return {string}
*/
var reverseWords = function(s) {
let i = 0;
let len = s.length;
s = s.split('');
while (i < len) {
let start = i;
while (i < len && s[i] !== ' ') {
i++;
}
let left = start;
let right = i - 1;
while (left < right) {
let tmp = s[left];
s[left] = s[right];
s[right] = tmp;
left++;
right--;
}
while (i < len && s[i] === ' ') {
i++
}
}
return s.join('');
};
网友评论