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--
	}
}
相关推荐
Live&&learn15 小时前
算法训练-数据结构
数据结构·算法·leetcode
电子_咸鱼17 小时前
【STL string 全解析:接口详解、测试实战与模拟实现】
开发语言·c++·vscode·python·算法·leetcode
麻辣兔变形记1 天前
基于 Go‑Zero 的用户 CRUD Demo:如何一步步从 MySQL + sqlx 演进为 PostgreSQL + GORM + 微服务架构
mysql·微服务·postgresql·架构·golang
i***27951 天前
【golang学习之旅】使用VScode安装配置Go开发环境
vscode·学习·golang
2501_941884611 天前
云计算与边缘计算:解锁未来计算架构的智能边界
leetcode
程序猿小白日记1 天前
云计算与物联网融合:推动智慧城市的未来发展
leetcode
吗~喽1 天前
【LeetCode】滑动窗口_水果成篮_C++
c++·算法·leetcode
小南家的青蛙1 天前
LeetCode面试题 04.06 后继者
算法·leetcode·职场和发展
无敌最俊朗@1 天前
力扣hot100 - 合并两个有序链表21
算法·leetcode·链表
墨染点香1 天前
LeetCode 刷题【168. Excel 表列名称】
算法·leetcode·职场和发展