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--
	}
}
相关推荐
1白天的黑夜11 小时前
栈-20.有效的括号-力扣(LeetCode)
c++·算法·leetcode
2301_766536052 小时前
刷leetcode hot100--矩阵6/1
算法·leetcode·矩阵
阳洞洞3 小时前
leetcode 455. Assign Cookies和2410. Maximum Matching of Players With Trainers
leetcode·贪心
前端拿破轮3 小时前
【代码随想录刷题总结】leetcode27-移除元素
算法·leetcode
钟离墨笺4 小时前
Go语言学习-->第一个go程序--hello world!
开发语言·学习·golang
march of Time4 小时前
go的工具库:github.com/expr-lang/expr
开发语言·golang·github
编程绿豆侠5 小时前
力扣HOT100之二分查找:74. 搜索二维矩阵
算法·leetcode·矩阵
fashia7 小时前
Java转Go日记(五十七):gin 中间件
开发语言·后端·golang·go·gin
余厌厌厌8 小时前
go语言学习 第5章:函数
开发语言·学习·golang·go