华为机试:单词倒排
试一下让ChatGPT写一个完整的题
#include <iostream> #include <vector> #include <string> using namespace std; string reverseWords(const string& sentence) { vector<string> words; string word; // 遍历字符串,将单词分割出来并存储到 vector 中 for (char c : sentence) { if (isalpha(c)) { word.push_back(c); } else if (!word.empty()) { words.push_back(word); word.clear(); } } if (!word.empty()) { words.push_back(word); } // 倒序遍历 vector,将单词拼接成一个字符串 string result; for (auto it = words.rbegin(); it != words.rend(); ++it) { result += *it; result.push_back(' '); } if (!result.empty()) { result.pop_back(); } return result; } int main() { // int a, b; // while (cin >> a >> b) { // 注意 while 处理多个 case // cout << a + b << endl; // } string str; getline(cin, str); cout << reverseWords(str) << endl; return 0; }