Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5b4249d

Browse files
committed
151.翻转字符串里的单词 新增使用了移除元素思想的 Go 版本
1 parent 842bafc commit 5b4249d

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

‎problems/0151.翻转字符串里的单词.md‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -467,9 +467,57 @@ class Solution:
467467
return " ".join(words)
468468
```
469469

470-
471470
Go:
472471

472+
版本一:
473+
474+
```go
475+
func reverseWords(s string) string {
476+
b := []byte(s)
477+
478+
// 移除前面、中间、后面存在的多余空格
479+
slow := 0
480+
for i := 0; i < len(b); i++ {
481+
if b[i] != ' ' {
482+
if slow != 0 {
483+
b[slow] = ' '
484+
slow++
485+
}
486+
for i < len(b) && b[i] != ' ' { // 复制逻辑
487+
b[slow] = b[i]
488+
slow++
489+
i++
490+
}
491+
}
492+
}
493+
b = b[0:slow]
494+
495+
// 翻转整个字符串
496+
reverse(b)
497+
// 翻转每个单词
498+
last := 0
499+
for i := 0; i <= len(b); i++ {
500+
if i == len(b) || b[i] == ' ' {
501+
reverse(b[last:i])
502+
last = i + 1
503+
}
504+
}
505+
return string(b)
506+
}
507+
508+
func reverse(b []byte) {
509+
left := 0
510+
right := len(b) - 1
511+
for left < right {
512+
b[left], b[right] = b[right], b[left]
513+
left++
514+
right--
515+
}
516+
}
517+
```
518+
519+
版本二:
520+
473521
```go
474522
import (
475523
"fmt"

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /