题解 | #翻转单词序列#
翻转单词序列
https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
#include <vector> class Solution { public: string ReverseSentence(string str) { if (str == "") { return ""; } // 将原来的str类型句子转换为每个单词和空格占一个元素的vector<string>类型 vector<char> word; vector<string> sentence; int i = 0; while (i <= str.size()) { if (str[i] == ' ' || i == str.size()) { string s; int j = 0; while (j < word.size()) { s += word[j]; ++j; } sentence.push_back(s); word.clear(); if (str[i] == ' ') { sentence.push_back(" "); } } else { word.push_back(str[i]); } ++i; } // 交换顺序 int k = 0; while (k < sentence.size() / 2) { string temp = sentence[k]; sentence[k] = sentence[sentence.size() - 1 - k]; sentence[sentence.size() - 1 - k] = temp; ++k; } // 将vector<string>类型转换为string类型以返回 string res; for (const string& s : sentence) { res += s; } return res; } };