Skip to content

Commit

Permalink
151.翻转字符串里的单词 新增使用了移除元素思想的 Go 版本
Browse files Browse the repository at this point in the history
  • Loading branch information
615lyw committed Jun 1, 2023
1 parent 842bafc commit 5b4249d
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion problems/0151.翻转字符串里的单词.md
Original file line number Diff line number Diff line change
Expand Up @@ -467,9 +467,57 @@ class Solution:
return " ".join(words)
```


Go:

版本一:

```go
func reverseWords(s string) string {
b := []byte(s)

// 移除前面、中间、后面存在的多余空格
slow := 0
for i := 0; i < len(b); i++ {
if b[i] != ' ' {
if slow != 0 {
b[slow] = ' '
slow++
}
for i < len(b) && b[i] != ' ' { // 复制逻辑
b[slow] = b[i]
slow++
i++
}
}
}
b = b[0:slow]

// 翻转整个字符串
reverse(b)
// 翻转每个单词
last := 0
for i := 0; i <= len(b); i++ {
if i == len(b) || b[i] == ' ' {
reverse(b[last:i])
last = i + 1
}
}
return string(b)
}

func reverse(b []byte) {
left := 0
right := len(b) - 1
for left < right {
b[left], b[right] = b[right], b[left]
left++
right--
}
}
```

版本二:

```go
import (
"fmt"
Expand Down

0 comments on commit 5b4249d

Please sign in to comment.