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--
	}
}
相关推荐
Flandern11116 分钟前
Go程序员学习AI大模型项目实战02:给 AI 装上“大脑”:从配置解包到流式生成的深度拆解
人工智能·后端·python·学习·golang
穿条秋裤到处跑6 分钟前
每日一道leetcode(2026.04.09):区间乘法查询后的异或 II
算法·leetcode
小欣加油23 分钟前
leetcode 42 接雨水
c++·算法·leetcode·职场和发展
cpp_25011 小时前
P1910 L 国的战斗之间谍
数据结构·c++·算法·题解·洛谷·背包dp
凌波粒2 小时前
LeetCode--459.重复的子字符串(字符串/KMP算法)
算法·leetcode·职场和发展
_深海凉_2 小时前
LeetCode热题100-移除元素
数据结构·算法·leetcode
米粒12 小时前
力扣算法刷题 Day 36
算法·leetcode·职场和发展
呼啦啦5613 小时前
leetcode练习——栈和队列
算法·leetcode·职场和发展
y = xⁿ4 小时前
【LeetCode】哈希表
算法·leetcode·散列表
北顾笙9804 小时前
day22-数据结构力扣
数据结构·算法·leetcode