Skip to content

Commit 0129bde

Browse files
authored
优化 0151.翻转字符串里的单词Go示例
1 parent 9c9ba93 commit 0129bde

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

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

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -546,26 +546,28 @@ func reverseWords(s string) string {
546546
b = b[:slowIndex]
547547
}
548548
//2.反转整个字符串
549-
reverse(&b, 0, len(b)-1)
549+
reverse(b)
550550
//3.反转单个单词 i单词开始位置,j单词结束位置
551551
i := 0
552552
for i < len(b) {
553553
j := i
554554
for ; j < len(b) && b[j] != ' '; j++ {
555555
}
556-
reverse(&b, i, j-1)
556+
reverse(b[i:j])
557557
i = j
558558
i++
559559
}
560560
return string(b)
561561
}
562562

563-
func reverse(b *[]byte, left, right int) {
564-
for left < right {
565-
(*b)[left], (*b)[right] = (*b)[right], (*b)[left]
566-
left++
567-
right--
568-
}
563+
func reverse(b []byte) {
564+
left := 0
565+
right := len(b) - 1
566+
for left < right {
567+
b[left], b[right] = b[right], b[left]
568+
left++
569+
right--
570+
}
569571
}
570572
```
571573

0 commit comments

Comments
 (0)