> For the complete documentation index, see [llms.txt](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/string/557.-reverse-words-in-a-string-iii.md).

# 557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

**Example 1:**<br>

```
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
```

**Note:** In the string, each word is separated by single space and there will not be any extra space in the string.

```cpp
// stringstream
string reverseWords(string s) { // time: O(n); space: O(n)
    istringstream is(s);
    string buf, res;
    while (is >> buf) {
        reverse(buf.begin(), buf.end());
        res += buf + " ";
    }
    return res.substr(0, res.length() - 1);
}
```

```cpp
string reverseWords(string s) { // time: O(n); space: O(n)
    int start = 0, end = 0, n = s.length();
    while (start < n && end < n) {
        while (end < n && s[end] != ' ') ++end;
        for (int i = start, j = end - 1; i < j; ++i, --j) {
            swap(s[i], s[j]);
        }
        start = ++end;
    }
    return s;
}
```

```cpp
string reverseWords(string s) { // time: O(n); space: O(n)
    int n = s.length(), i = 0, j = 0;
    while (j < n) {
        while (j < n && s[j] != ' ') ++j;
        reverse(s.begin() + i, s.begin() + j);
        i = j + 1;
        j = i;
    }
    return s;
}
```
