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--
	}
}
相关推荐
pyz6665 小时前
LeetCode - Hot 100 - 滑动窗口最大值
leetcode
胡萝卜的兔5 小时前
go使用voidint实现版本切换
开发语言·chrome·golang
8Qi86 小时前
LeetCode 300 & 674:最长递增子序列 vs 最长连续递增子序列
算法·leetcode·职场和发展·动态规划
sheeta19986 小时前
LeetCode 补拙笔记 日期:2026.06.07 题目:283. 移动零
笔记·算法·leetcode
8Qi87 小时前
LeetCode 188 & 123:股票买卖问题(限制交易次数)—— 联合题解
算法·leetcode·职场和发展·动态规划
一只齐刘海的猫7 小时前
【Leetcode】三数之和
数据结构·算法·leetcode
jieyucx7 小时前
站在云原生高并发天花板:拆解 Go 语言 GMP 模型与 I/O 多路复用的神级配合
开发语言·云原生·golang
sheeta19987 小时前
LeetCode 补拙笔记 日期:2026.06.07 题目:49. 字母异位词分组
笔记·算法·leetcode
白露与泡影7 小时前
SEATA:Server 到 Golang Client 全链路走读
开发语言·后端·golang
小小龙学IT7 小时前
Go 后端开发实战:构建高性能 RESTful API 服务
开发语言·golang·restful