LeetCode-剑指58-I.翻转单词顺序

在这里插入图片描述

1、自定义split

我们可以通过自定义一个split函数,将字符串分割成多个字符串构成的数组。而后我们将数组中的内容逆序输出加入到结果的字符串中即可。

class Solution {
public:
    vector<string> split(string s, char target) {
        int low = 0, high, n = s.size();
        vector<string> words;
        while (low < n) {
            while (s[low] == target) ++low;
            if (low >= n) break;
            high = low + 1;
            while (s[high] != target && high < n) ++high;
            words.emplace_back(s.substr(low, high - low));
            low = high;
        }
        return words;
    }

    string reverseWords(string s) {
        string res;
        vector<string> words = split(s, ' ');
        reverse(words.begin(), words.end());
        for (string s: words) {
            if (!res.empty()) res += " ";
            res += s;
        }
        return res;
    }
};

2、双端队列

我们可以利用一个双端队列来实现字符串的逆序。我们首先去除字符串中的空格,而后将读入的单词加入队列的头部,而后我们不断循环从队列中弹出单词即可。

class Solution {
public:
    string reverseWords(string s) {
        int left = 0, right = s.size() - 1;
        while (left <= right && s[left] == ' ') ++left;
        while (left <= right && s[right] == ' ') --right;

        deque<string> d;
        string word;

        while (left <= right) {
            char c = s[left];
            if (word.size() && c == ' ') {
                d.push_front(move(word));
                word = "";
            }
            else if (c != ' ') {
                word += c;
            }
            ++left;
        }
        d.push_front(move(word));
        
        string ans;
        while (!d.empty()) {
            ans += d.front();
            d.pop_front();
            if (!d.empty()) ans += ' ';
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值