go版本新解法:双指针逆序遍历,时间复杂度O(n),空间复杂度O(n)

This commit is contained in:
1ltwo
2025-01-03 10:11:06 +08:00
parent 6973320e93
commit aa2450222d

View File

@ -639,7 +639,46 @@ func reverse(b []byte) {
}
}
```
```go
//双指针解法。指针逆序遍历,将遍历后得到的单词(间隔为空格,用以区分)顺序放置在额外空间
//时间复杂度O(n)空间复杂度O(n)
func reverseWords(s string) string {
strBytes := []byte(s)
n := len(strBytes)
// 记录有效字符范围的起始和结束位置
start, end := 0, n-1
// 去除开头空格
for start < n && strBytes[start] == 32 {
start++
}
// 处理全是空格或空字符串情况
if start == n {
return ""
}
// 去除结尾空格
for end >= 0 && strBytes[end] == 32 {
end--
}
// 结果切片,预分配容量
res := make([]byte, 0, end-start+1)//这里挺重要的,本人之前没有预分配容量,每次循环都添加单词,导致内存超限(也可能就是我之前的思路有问题)
// 从后往前遍历有效字符范围
for i := end; i >= start; {
// 找单词起始位置,直接通过循环条件判断定位
for ; i >= start && strBytes[i] == 32; i-- {
}
j := i
for ; j >= start && strBytes[j]!= 32; j-- {
}
res = append(res, strBytes[j+1:i+1]...)
// 只在不是最后一个单词时添加空格
if j > start {
res = append(res, 32)
}
i = j
}
return string(res)
}
```
### JavaScript: