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--
	}
}
相关推荐
希望我万事顺遂14 小时前
力扣hot100-滑动窗口最大值
数据结构·算法·leetcode
喵了几个咪14 小时前
GoWind Flow 拆解:一个 Go 工作流引擎与它的双模式设计器
开发语言·人工智能·后端·golang
codeejun14 小时前
每日一Go·MySQL-14、慢 SQL 产生原因全解
sql·mysql·golang
是main不是漫15 小时前
【双指针|LeetCode1089 复写零】巧用逆向思路,破解原地覆盖陷阱
数据结构·算法·leetcode
Pniubi1 天前
力扣76.最小覆盖子串
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode2541~2560题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2481~2500题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2461~2480题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2441~2460题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2521~2540题目解析
java·leetcode