刷题记录第三十四天-反转字符串中的单词

class Solution {
public:
    string reverseWords(string s) {
        int slow=0;
        for(int fast=0;fast<s.size();fast++){
            if(s[fast]!=' '){
                if(slow!=0)s[slow++]=' ';
                while(s[fast]!=' '&&fast<s.size()){
                    s[slow++]=s[fast++];
                }
            }
        }
        s.resize(slow);
        int left=0,right=s.size()-1;
        while(left<right){
            char c = s[right];
            s[right--] = s[left];
            s[left++] = c;
        }
        left=0;
        for(int i=1;i<s.size();i++){
            if(s[i]==' '){
                right=i-1;
                while(left<right){
                    char c = s[right];
                    s[right--] = s[left];
                    s[left++] = c;
                }
                left=i+1;
            }
        }
        right=s.size()-1;
        while(left<right){
            char c = s[right];
            s[right--] = s[left];
            s[left++] = c;
        }
        return s;
    }
};

你可能感兴趣的:(每日一题,java,算法,数据结构)