给定一个字符串,逐个翻转字符串中的每个单词。

力扣解析:https://leetcode-cn.com/problems/reverse-words-in-a-string/solution/fan-zhuan-zi-fu-chuan-li-de-dan-ci-by-leetcode-sol/

方法一:时间复杂度O(n),空间复杂度O(N)

另外申请了空间

class Solution {
public:
        string reverseWords(string s) {
        string res;
        if(s.empty())
            return res;
        int i = s.size() - 1;
        while(i>=0)
        {
            if (isgraph(s[i]))
            {
                string temp;
                while (i >= 0 && isgraph(s[i]))
                {
                    temp += s[i];
                    --i;
                }
                string st(temp.rbegin(), temp.rend());
                res += st;
                res += ' ';
                temp.clear();
            }
            else
                --i;
        }
        if(!(res.empty()))
            res.pop_back();
        return res;
    }

};

方法2:原地翻转,时间复杂度O(N),空间复杂度O(1)

class Solution {
public:
    string reverseWords(string s) {
        // 反转整个字符串
        reverse(s.begin(), s.end());

        int n = s.size();
        int idx = 0;
        for (int start = 0; start < n; ++start) {
            if (s[start] != ' ') {
                // 填一个空白字符然后将idx移动到下一个单词的开头位置
                if (idx != 0) s[idx++] = ' ';

                // 循环遍历至单词的末尾
                int end = start;
                while (end < n && s[end] != ' ') s[idx++] = s[end++];

                // 反转整个单词
                reverse(s.begin() + idx - (end - start), s.begin() + idx);

                // 更新start,去找下一个单词
                start = end;
            }
        }
        s.erase(s.begin() + idx, s.end());
        return s;
    }
};