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--
	}
}
相关推荐
__AtYou__2 小时前
Golang | Leetcode Golang题解之第448题找到所有数组中消失的数字
leetcode·golang·题解
转调2 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
千年死缓3 小时前
go+redis基于tcp实现聊天室
redis·tcp/ip·golang
huanxiangcoco4 小时前
152. 乘积最大子数组
python·leetcode
希望有朝一日能如愿以偿5 小时前
力扣题解(飞机座位分配概率)
算法·leetcode·职场和发展
Espresso Macchiato5 小时前
Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
leetcode·滑动窗口·leetcode medium·leetcode 3306·leetcode周赛417
数据分析螺丝钉7 小时前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
￴ㅤ￴￴ㅤ9527超级帅7 小时前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
吃着火锅x唱着歌7 小时前
Redis设计与实现 学习笔记 第五章 跳跃表
golang
鱼跃鹰飞7 小时前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试