s[i] is an English letter (uppercase or lowercase), digit, or space ' '.
There is at least one word in s.
s does not contain leading or trailing spaces.
All the words in s are guaranteed to be separated by a single space.
Solutions
Solution 1: Two Pointers
We can iterate through the character array \(s\), using two pointers \(i\) and \(j\) to find the start and end positions of each word, then reverse each word, and finally reverse the entire character array.
The time complexity is \(O(n)\), where \(n\) is the length of the character array \(s\). The space complexity is \(O(1)\).
/** Do not return anything, modify s in-place instead. */functionreverseWords(s:string[]):void{constn=s.length;constreverse=(i:number,j:number):void=>{for(;i<j;++i,--j){[s[i],s[j]]=[s[j],s[i]];}};for(leti=0,j=0;j<=n;++j){if(s[j]===' '){reverse(i,j-1);i=j+1;}elseif(j===n-1){reverse(i,j);}}reverse(0,n-1);}