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--
	}
}
相关推荐
xy_recording2 小时前
Day08 Go语言学习
开发语言·学习·golang
吧唧霸3 小时前
golang读写锁和互斥锁的区别
开发语言·算法·golang
1白天的黑夜14 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
上海迪士尼354 小时前
力扣子集问题C++代码
c++·算法·leetcode
熬了夜的程序员4 小时前
【LeetCode】16. 最接近的三数之和
数据结构·算法·leetcode·职场和发展·深度优先
Miraitowa_cheems4 小时前
LeetCode算法日记 - Day 15: 和为 K 的子数组、和可被 K 整除的子数组
java·数据结构·算法·leetcode·职场和发展·哈希算法
无聊的小坏坏18 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学
浮灯Foden1 天前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
执子手 吹散苍茫茫烟波1 天前
leetcode415. 字符串相加
java·leetcode·字符串