---
description: https://leetcode.com/problems/reverse-words-in-a-string/description/
---

# 151. Reverse Words in a String

把str以word为基础元素做翻转，并且结果是trim过的且单词之间只能有一个空格。比如"the people"变成了"people the"，最后6个字符放在了前面6个位置，因此先对整个str做字符为基准的翻转。此时每个单词所在的位置是对的，但单词内部是反的。对每个单词内部做翻转用两个前后指针。最后再对空格做下特殊处理。虽然由于substr的原因实现不是真的in-place，但思想是一致的。

```cpp
/*
 * @lc app=leetcode id=151 lang=cpp
 *
 * [151] Reverse Words in a String
 */

// @lc code=start
class Solution {
public:
    string reverseWords(string s) {
        reverse(s.begin(), s.end());
        int l = -1, r = 0, N = s.length();
        while (r < N && s[r] == ' ') {
            ++r;
        }
        while (N > 0 && s[N - 1] == ' ') {
            --N;
        }
        while (r < N) {
            if (l == -1 && s[r] != ' ') l = r; 
            if ((r < N - 1 && s[r + 1] != ' ') || (l == -1 && s[r] == ' ')) {
                ++r;
                continue;
            }
            int tr = r;
            while (l < r) {
                swap(s[l++], s[r--]);
            }
            r = tr + 1;
            l = -1;
        }
        l = r = 0;
        while (r < N && s[r] == ' ') {
            ++r;
        }
        while (r < N) {
            if (s[r] == ' ' && (r < N - 1 && s[r + 1] == ' ')) {
                ++r;
                continue;
            }
            s[l++] = s[r++];
        }
        while (l > 0 && s[l - 1] == ' ') {
            --l;
        }
        return s.substr(0, l);
    }
};
// @lc code=end


```
