v4if / blog

:octocat: 用issues写博客,记录点滴
35 stars 7 forks source link

单词翻转 #31

Open v4if opened 6 years ago

v4if commented 6 years ago

局部reverse -> 整体reverse

#include <iostream>
#include <string>
#include <cassert>

using namespace std;
void reverse(string& str, int p, int q) {
    assert(p >= 0 && q >= 0 && p <= q && q < str.size());
    while (p < q) {
        swap(str[p], str[q]);
        p++;
        q--;
    }
}

void sentence_reverse(string& str) {
    int size = str.size();

    for (int i = 0; i < size; i++) {
        while(i < size && str[i] == ' ') i++;

        int word_begin = i;
        while (i < size && str[i] != ' ') i++;
        reverse(str, word_begin, i - 1);
    }
    reverse(str, 0, size - 1);
}

int main()
{
    string str{"I am a student."};
    sentence_reverse(str);
    cout << str << endl;
    cout << "Hello World" << endl;
    return 0;
}