代码改变世界

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

2020-11-29 01:22  woshihuangrulin  阅读(75)  评论(0编辑  收藏  举报

使用快慢指针,注意循环结束后快指针比慢指针大的情况,此时应该将最后一个单词加入到结果中

class Solution {
public:
    string reverseWords(string s) {
        if (s.empty()) {
            return s;
        }

        int start = -1;
        vector<string> result_vec;
        string result;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] != ' ') {
                start = i;
                break;
            }
        }

        if (start == -1) {
            return result;
        }

        int slow = start;
        int fast = start;
        while (fast < s.size()) {
            if (s[slow] != ' ' && s[fast] != ' ') {
                fast++;
            }
            else if (s[slow] != ' ' && s[fast] == ' '){
                result_vec.emplace_back(s.substr(slow, fast - slow));
                slow = fast;
            }
            else if (s[slow] == ' ' && s[fast] == ' ') {
                slow++;
                fast++;
            }
        }

        if (fast > slow) {
            result_vec.emplace_back(s.substr(slow, fast - slow));
        }

        for (int i = result_vec.size() - 1; i > 0; i--) {
            result = result + result_vec[i] + " ";
        }
        return result + result_vec[0];
    }
};