557. Reverse Words in a String I
2021-12-03 本文已影响0人
jluemmmm
反转句子形式的字符串
- 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('');
};