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 36 37 38 39 40
| function reverseWords(s: string): string { const strArr = s.split('') removeExtraSpaces(strArr) const len = strArr.length reverse(strArr, 0, len - 1) let start = 0 for (let i = 0; i <= len; i++) { if (strArr[i] === ' ' || i === len) { reverse(strArr, start, i - 1) start = i + 1 } } return strArr.join('') }
function removeExtraSpaces(strArr: string[]) { let slow = 0, fast = 0 while (fast < strArr.length) { if (strArr[fast] === ' ' && (fast === 0 || strArr[fast - 1] === ' ')){ fast++ } else { strArr[slow++] = strArr[fast++] } } strArr.length = strArr[slow - 1] === ' ' ? slow - 1 : slow }
function reverse(strArr: string[], start: number, end: number) { while (start < end) { [strArr[start], strArr[end]] = [strArr[end], strArr[start]] start++ end-- } }
|