题解 | #翻转单词序列#

翻转单词序列

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

全部评论

相关推荐

MingoTree:看不出你你的技术栈,想找什么工作,然后课设项目别写上去了,自我评价删了,前后端你想好你要干啥,这种简历投上去秒挂的
点赞 评论 收藏
分享
kl_我是东山啊:《相关公司:阿里巴巴》
投递阿里巴巴等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务