151. 反转字符串中的单词

发布时间 2023-10-07 11:20:01作者: CuriosityWang

LeetCode题目:https://leetcode.cn/problems/reverse-words-in-a-string/description/
image

class Solution {
public:
    void reverse(string& s, int start, int end){ //翻转,区间写法:左闭右闭 []
        for(;start < end; start++, end--){
            swap(s[start], s[end]);
        }
    }

    void removeExtraSpaces(string& s) {
        // 去除所有空格并在相邻单词之间添加空格, 快慢指针。
        // fast指针指向要寻找的元素,slow指向fast指针找到元素的位置。
        int slow = 0;
        for(int fast = 0; fast < s.length(); fast++){
            // detect one word
            if(s[fast]!= ' '){
                // 对于非首单词,添加一个空格
                if(slow != 0) s[slow++] = ' ';
                // 先书写去掉所有的空格
                while(s[fast] != ' ' && fast < s.length()){
                    s[slow++] = s[fast++];
                }
            }
        }
        s.resize(slow);
    }

    string reverseWords(string s) {
        removeExtraSpaces(s);
        reverse(s, 0, s.length()-1);
        // 局部单词反转
        for(int i = 0; i < s.length(); i++){
            if(s[i] != ' '){
                int count = i;
                while(s[count] != ' ' && count != s.length()){
                    count++;
                }
                reverse(s, i, count-1);
                i = count;
            }
        }

        return s;
    }

};