• Time:O(n)
• Space:O(1)

## C++

``````class Solution {
public:
void reverseWords(vector<char>& s) {
reverse(begin(s), end(s));  // reverse the whole string
reverseWords(s, s.size());  // reverse each word
}

private:
void reverseWords(vector<char>& s, int n) {
int i = 0;
int j = 0;

while (i < n) {
while (i < j || i < n && s[i] == ' ')  // skip spaces
++i;
while (j < i || j < n && s[j] != ' ')  // skip non spaces
++j;
reverse(begin(s) + i, begin(s) + j);  // reverse the word
}
}
};
``````

## JAVA

``````class Solution {
public void reverseWords(char[] s) {
reverse(s, 0, s.length - 1); // reverse the whole string
reverseWords(s, s.length);   // reverse each word
}

private void reverse(char[] s, int l, int r) {
while (l < r) {
final char c = s[l];
s[l++] = s[r];
s[r--] = c;
}
}

private void reverseWords(char[] s, int n) {
int i = 0;
int j = 0;

while (i < n) {
while (i < j || i < n && s[i] == ' ') // skip spaces
++i;
while (j < i || j < n && s[j] != ' ') // skip non spaces
++j;
reverse(s, i, j - 1); // reverse the word
}
}
}
``````

## Python

``````class Solution:
def reverseWords(self, s: List[str]) -> None:
def reverse(l: int, r: int) -> None:
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1

def reverseWords(n: int) -> None:
i = 0
j = 0

while i < n:
while i < j or (i < n and s[i] == ' '):  # skip spaces
i += 1
while j < i or (j < n and s[j] != ' '):  # skip non spaces
j += 1
reverse(i, j - 1)  # reverse the word

reverse(0, len(s) - 1)  # reverse the whole string
reverseWords(len(s))  # reverse each word
``````