Golang | Leetcode Golang题解之第151题反转字符串中的单词

题目:

题解:

Go 复制代码
import (
	"fmt"
)

func reverseWords(s string) string {
	//1.使用双指针删除冗余的空格
	slowIndex, fastIndex := 0, 0
	b := []byte(s)
	//删除头部冗余空格
	for len(b) > 0 && fastIndex < len(b) && b[fastIndex] == ' ' {
		fastIndex++
	}
    //删除单词间冗余空格
	for ; fastIndex < len(b); fastIndex++ {
		if fastIndex-1 > 0 && b[fastIndex-1] == b[fastIndex] && b[fastIndex] == ' ' {
			continue
		}
		b[slowIndex] = b[fastIndex]
		slowIndex++
	}
	//删除尾部冗余空格
	if slowIndex-1 > 0 && b[slowIndex-1] == ' ' {
		b = b[:slowIndex-1]
	} else {
		b = b[:slowIndex]
	}
	//2.反转整个字符串
	reverse(&b, 0, len(b)-1)
	//3.反转单个单词  i单词开始位置,j单词结束位置
	i := 0
	for i < len(b) {
		j := i
		for ; j < len(b) && b[j] != ' '; j++ {
		}
		reverse(&b, i, j-1)
		i = j
		i++
	}
	return string(b)
}

func reverse(b *[]byte, left, right int) {
	for left < right {
		(*b)[left], (*b)[right] = (*b)[right], (*b)[left]
		left++
		right--
	}
}
相关推荐
啊哦呃咦唔鱼9 分钟前
LeetCode双指针合集
算法·leetcode·职场和发展
alphaTao32 分钟前
LeetCode 每日一题 2026/4/13-2026/4/19
算法·leetcode·职场和发展
Tomhex3 小时前
Go调用C代码的场景与实践
golang
f3iiish3 小时前
3783. 整数的镜像距离 力扣
算法·leetcode
小雅痞4 小时前
[Java][Leetcode hard] 135. 分发糖果
java·算法·leetcode
黑牛儿4 小时前
Swoole协程 vs Go协程:PHP开发者一看就懂的实战对比
后端·golang·php·swoole
嘻嘻哈哈樱桃4 小时前
数据流中的中位数 力扣--160
算法·leetcode·职场和发展
j_xxx404_4 小时前
力扣算法题:字符串(最长公共前缀|最长回文子串)
c++·算法·leetcode
人道领域4 小时前
【LeetCode刷题日记】:344,541-字符串反转字符串反转技巧:双指针原地交换法
算法·leetcode·面试
Wenweno0o13 小时前
Eino-Document 组件使用指南
golang·大模型·智能体·eino