# 186. Reverse Words in a String II

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/reverse-words-in-a-string-ii/

> 内容描述

```
Given an input string , reverse the string word by word. 

Example:

Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
Note: 

A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
Follow up: Could you do it in-place without allocating extra space?
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

slicing itself creates a deep copy of  `str`, so using O(N) extra space

```python
class Solution:
    def reverseWords(self, str):
        """
        :type str: List[str]
        :rtype: void Do not return anything, modify str in-place instead.
        """
        lst = (''.join(str[:])).split(' ')[::-1]
        str[:] = list(' '.join(lst))
```



> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

自己写一个reverse函数，然后先对整个list做reverse，再对每一个word做reverse即可, beats 87.21%

```python
class Solution:
    def reverseWords(self, str):
        """
        :type str: List[str]
        :rtype: void Do not return anything, modify str in-place instead.
        """
        def reverse(s, start, end):
            while start < end:
                s[start], s[end] = s[end], s[start]
                start += 1
                end -= 1
                
        reverse(str, 0, len(str) - 1)
        idx = 0
        for i in range(len(str)):
            if str[i] == ' ':
                reverse(str, idx, i - 1)
                idx = i + 1
            elif i == len(str) - 1:
                reverse(str, idx, i)
```



































