# 120 - 557 反转字符串中的单词3

## 题目

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

示例 1:

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

注意：在字符串中，每个单词由单个空格分隔，并且字符串中不会有任何额外的空格。

## 解答

第一反应，用空格拆成数组，然后一个个反转，然后再拼回来？

```javascript
var reverseWords = function(s) {
  let res = ""
  s.split(' ').forEach(e => {
    res += " " + e.split('').reverse().join('')
  })
  return res.slice(1)
};
```

> Runtime: 68 ms, faster than 94.16% of JavaScript online submissions for Reverse Words in a String III.
>
> Memory Usage: 41.4 MB, less than 95.65% of JavaScript online submissions for Reverse Words in a String III.

感觉。第一反应的效率还不错？

```python
class Solution:
    def reverseWords(self, s: str) -> str:
        return ' '.join(s.split(' ')[::-1])[::-1]
```

> Runtime: 32 ms, faster than 97.92% of Python3 online submissions for Reverse Words in a String III.
>
> Memory Usage: 14.3 MB, less than 7.69% of Python3 online submissions for Reverse Words in a String III.

```go
func reverseWords(s string) string {
    words := strings.Fields(s)
    str := ""
    for _, word := range words {
        for i := len(word) - 1; i >= 0; i-- {
            str += string(word[i])
        }
        str += " "
    }
    return strings.TrimSpace(str)
}
```

> Runtime: 524 ms, faster than 5.81% of Go online submissions for Reverse Words in a String III.
>
> Memory Usage: 8.3 MB, less than 100.00% of Go online submissions for Reverse Words in a String III.
