华为机试:单词倒排

试一下让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;
}

全部评论

相关推荐

05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
05-23 20:31
已编辑
武汉大学 Java
内向的柠檬精在研究求职打法:注意把武大标粗标大 本地你俩不是乱杀
点赞 评论 收藏
分享
评论
1
8
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务