翻转字符串中的单词

给定一个字符串,逐个翻转字符串中的每个单词。

样例
给出s = “the sky is blue”,返回"blue is sky the"

说明
单词的构成:无空格字母构成一个单词
输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括
如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个

#include <iostream>
#include <string.h>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;

string reverseWords(string &s) {

    int i = s.size()-1;
    string res;
    while (i >= 0) {
        while (i >= 0 && s[i] == ' ') {
            i--;
        }

        if (i < 0) break;
        if (res.size() != 0) {
            res.append(" ");
        }
        string temp;
        while (i >= 0 && s[i] != ' ') {
            temp.push_back(s[i]);
            i--;
        }
        reverse(temp.begin(), temp.end());
        res.append(temp);
    }
    return res;
}

int main() {
    string s;
    getline(cin, s);
    cout << reverseWords(s) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_32273417/article/details/86673655