File tree Expand file tree Collapse file tree 1 file changed +40
-1
lines changed Expand file tree Collapse file tree 1 file changed +40
-1
lines changed Original file line number Diff line number Diff line change @@ -639,7 +639,46 @@ func reverse(b []byte) {
639639 }
640640}
641641```
642-
642+ ``` go
643+ // 双指针解法。指针逆序遍历,将遍历后得到的单词(间隔为空格,用以区分)顺序放置在额外空间
644+ // 时间复杂度O(n),空间复杂度O(n)
645+ func reverseWords (s string ) string {
646+ strBytes := []byte (s)
647+ n := len (strBytes)
648+ // 记录有效字符范围的起始和结束位置
649+ start , end := 0 , n-1
650+ // 去除开头空格
651+ for start < n && strBytes[start] == 32 {
652+ start++
653+ }
654+ // 处理全是空格或空字符串情况
655+ if start == n {
656+ return " "
657+ }
658+ // 去除结尾空格
659+ for end >= 0 && strBytes[end] == 32 {
660+ end--
661+ }
662+ // 结果切片,预分配容量
663+ res := make ([]byte , 0 , end-start+1 )// 这里挺重要的,本人之前没有预分配容量,每次循环都添加单词,导致内存超限(也可能就是我之前的思路有问题)
664+ // 从后往前遍历有效字符范围
665+ for i := end; i >= start; {
666+ // 找单词起始位置,直接通过循环条件判断定位
667+ for ; i >= start && strBytes[i] == 32 ; i-- {
668+ }
669+ j := i
670+ for ; j >= start && strBytes[j]!= 32 ; j-- {
671+ }
672+ res = append (res, strBytes[j+1 :i+1 ]...)
673+ // 只在不是最后一个单词时添加空格
674+ if j > start {
675+ res = append (res, 32 )
676+ }
677+ i = j
678+ }
679+ return string (res)
680+ }
681+ ```
643682
644683
645684### JavaScript:
You can’t perform that action at this time.
0 commit comments