题解 | #翻转单词序列#

翻转单词序列

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;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-08 17:10
点赞 评论 收藏
分享
07-09 18:28
门头沟学院 Java
写着提前批,结果还要实习4个月以上???
程序员牛肉:这种不用看,直接投了,面试的时候问对应的HR就行。有可能他们是直接复制的暑期实习的模板。
点赞 评论 收藏
分享
程序员牛肉:这一眼假啊,基本上都是骗人的,不然就涉及到职位贪腐了,就像之前华为的OD事件,看你运气好不好了
点赞 评论 收藏
分享
Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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