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--
	}
}
相关推荐
Shaoshing9 小时前
LeetCode 921.使括号括号有效的最少添加
java·算法·leetcode·职场和发展
圣保罗的大教堂11 小时前
leetcode 3884. 双端字符匹配 简单
leetcode
SailingCoder13 小时前
Go 线上偶发数据错乱:值拷贝、slice、并发 map 的识别与规避
开发语言·后端·golang
codeejun14 小时前
每日一Go·MySQL-28、账户转账事务设计
开发语言·mysql·golang
Shaoshing15 小时前
LeetCode100 76.最小覆盖字串
java·算法·leetcode
microrain17 小时前
设备说 128.7,平台存了 100
物联网·golang·物模型·sagooiot
Navigator_Z18 小时前
LeetCode //C - 1331. Rank Transform of an Array
c语言·算法·leetcode
Tisfy18 小时前
LeetCode 1202.交换字符串中的元素:分组排序(连通图)
算法·leetcode·字符串·bfs·题解·排序·连通图
利威尔xu1 天前
Go map 并发十连问:多 goroutine 同时读写触发 fatal error,进程直接崩溃
开发语言·golang
喵了几个咪1 天前
GoWind Admin 拆解:智能问数——从一句自然语言到一张可信图表
ai·golang·llm·智能问数·gowind