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--
	}
}
相关推荐
小白程序员成长日记2 小时前
2025.12.03 力扣每日一题
算法·leetcode·职场和发展
元亓亓亓2 小时前
LeetCode热题100--20. 有效的括号--简单
linux·算法·leetcode
熊猫_豆豆2 小时前
LeetCode 49.字母异位组合 C++解法
数据结构·算法·leetcode
小武~3 小时前
Leetcode 每日一题C 语言版 -- 234 basic calculator
linux·c语言·leetcode
小白程序员成长日记3 小时前
2025.12.02 力扣每日一题
数据结构·算法·leetcode
吃着火锅x唱着歌4 小时前
LeetCode 3583.统计特殊三元组
算法·leetcode·职场和发展
狐575 小时前
2025-12-04-LeetCode刷题笔记-2211-统计道路上的碰撞次数
笔记·算法·leetcode
源代码•宸5 小时前
100 Go Mistakes(#4 过度使用getter和setter、#5 接口污染)
开发语言·经验分享·后端·golang
小南家的青蛙6 小时前
LeetCode第773题 - 滑动谜题
算法·leetcode·职场和发展
CoderYanger6 小时前
动态规划算法-子序列问题(数组中不连续的一段):30.最长数对链
java·算法·leetcode·动态规划·1024程序员节