华为机试:单词倒排

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

全部评论

相关推荐

头像
04-17 09:29
已编辑
湖南农业大学 后端
睡姿决定发型丫:本硕末9也是0offer,简历挂了挺多,只有淘天 美团 中兴给了面试机会,淘天二面挂,美团一面kpi面,中兴一面感觉也大概率kpi(虽然国企,但一面0技术纯聊天有点离谱吧)
点赞 评论 收藏
分享
评论
1
8
分享

创作者周榜

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