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--
	}
}
相关推荐
一只理智恩4 小时前
AI 实战应用:从“搜索式问答“到“理解式助教“
人工智能·python·语言模型·golang
iAkuya8 小时前
(leetcode)力扣100 73柱状图中最大的矩形(单调栈)
算法·leetcode·职场和发展
王老师青少年编程8 小时前
2020年信奥赛C++提高组csp-s初赛真题及答案解析(阅读程序第1题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
逆境不可逃8 小时前
【春节篇】LeetCode 热题 100 之 238.除了自身以外数组的乘积
数据结构·算法·leetcode
alexwang2119 小时前
B2007 A + B 问题 题解
c++·算法·题解·洛谷
呆萌很10 小时前
Go语言变量定义指南:从入门到精通
golang
Zik----10 小时前
Leetcode2 —— 链表两数相加
数据结构·c++·leetcode·链表·蓝桥杯
踩坑记录11 小时前
leetcode hot100 46. 全排列 medium 递归回溯 dfs
leetcode·深度优先
逆境不可逃11 小时前
LeetCode 热题 100 之 76.最小覆盖子串
java·算法·leetcode·职场和发展·滑动窗口
踩坑记录12 小时前
leetcode hot100 78. 子集 递归回溯 medium 位运算法
leetcode