Contents

# 151. Reverse Words in a String

## 題目 :

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

### Example :

Note

Input: s = “the sky is blue”

Output: “blue is sky the”

Input: s = " hello world "

Output: “world hello”

Input: s = “a good example”

Output: “example good a”

Input: s = " Bob Loves Alice "

Output: “Alice Loves Bob”

Input: s = “Alice does not even like bob”

Output: “bob like even not does Alice”

#### 解題思路 :

• 這題剛好把一些string的操作都包含進去了
1. 刪除多餘的空白
2. 翻轉字串
3. 翻轉單詞

• 刪除多餘的空白可以使用two pointers，首先將一個pointer fast放到一次出現字母出現的位置，再來將另一個pointer slow放在起點的位置，然後開始將fast的值搬到slow，開始同步往後走清除頭部的多餘空白，做一些條件控管，讓連續出現的空白才略過，單一個就繼續複製，可以達到每一個單詞之間留有一個空白的效果 及刪除掉單詞之間多餘的空白，最後再取slice到最後單詞出現的地方，就可以刪除到尾端的空白
• 再來翻轉整個字串
• 最後再執行一些條件控制，讓單詞一個一個翻轉回來就會得到所要的答案

### 以下是我的解法 - time complexity: O(n) , space complexity: O(1)

Runtime: 0 ms, faster than 100.00% of Go online submissions for Reverse Words in a String.

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 `````` `````` func reverseWords(s string) string { arr := []byte(s) fastIndex, slowIndex := 0, 0 // 1. 刪除多餘空白 for arr[fastIndex] == ' ' { fastIndex++ } for ;fastIndex < len(arr); fastIndex++ { if fastIndex > 0 && arr[fastIndex] == ' ' && arr[fastIndex-1] == arr[fastIndex] { continue } arr[slowIndex] = arr[fastIndex] slowIndex++ } if slowIndex > 0 && arr[slowIndex-1] == ' ' { arr = arr[:slowIndex-1] }else { arr = arr[:slowIndex] } // 2. 反轉整個字串 reverse(&arr, 0, len(arr)-1) // 3. 反轉所有單詞 i := 0 for i < len(arr) { j := i for ; i < len(arr) && arr[i] != ' ' ; i++ { } reverse(&arr, j, i-1) i++ } return string(arr) } func reverse(arr *[]byte, start int, end int) { for start < end { (*arr)[start], (*arr)[end] = (*arr)[end], (*arr)[start] start++ end-- } } ``````