557. 反转字符串中的单词 III

题目:给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例:

输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"

1.原创

class Solution {
public:
    string reverseString(string ss){
        int n = ss.size();
        for (int i=0,j=n-1;i<j;++i,--j){
            swap(ss[i],ss[j]); 
        }
        return ss;
    }
    string reverseWords(string s) {
        string res;
        string temp;
        for (auto i:s){  //string对象的索引返回是char型
            if (i !=' ') //空格是char类型也就是' '而不是string类型
                temp += i;
            else{
                res += reverseString(temp);
                res += ' ';
                temp = "";
            }
        }
        res += reverseString(temp);
        return res;

    }
};

2.题解

class Solution {
public: 
    string reverseWords(string s) {
        int length = s.length();
        int i = 0;
        while (i < length) {
            int start = i;
            while (i < length && s[i] != ' ') {
                i++;
            }

            int left = start, right = i - 1;
            while (left < right) {
                swap(s[left], s[right]);
                left++;
                right--;
            }
            while (i < length && s[i] == ' ') {
                i++;
            }
        }
        return s;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/solution/fan-zhuan-zi-fu-chuan-zhong-de-dan-ci-iii-by-lee-2/
原文地址:https://www.cnblogs.com/USTC-ZCC/p/14473181.html