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 小时前
GoLang八股(Go语言基础)
开发语言·后端·golang·map·defer·recover·panic
尋有緣1 小时前
力扣1355-活动参与者
大数据·数据库·leetcode·oracle·数据库开发
Morwit2 小时前
*【力扣hot100】 647. 回文子串
c++·算法·leetcode
iso少年3 小时前
Go 语言并发编程核心与用法
开发语言·后端·golang
菜鸟233号3 小时前
力扣96 不同的二叉搜索树 java实现
java·数据结构·算法·leetcode
千金裘换酒4 小时前
Leetcode 有效括号 栈
算法·leetcode·职场和发展
空空潍4 小时前
hot100-最小覆盖字串(day12)
数据结构·算法·leetcode
POLITE37 小时前
Leetcode 142.环形链表 II JavaScript (Day 10)
javascript·leetcode·链表
王老师青少年编程8 小时前
2025年12月GESP(C++)考级真题及详细题解(汇总版)
c++·题解·真题·gesp·csp·信奥赛·考级
千金裘换酒9 小时前
Leetcode 二叉树中序遍历 前序遍历 后序遍历(递归)
算法·leetcode·职场和发展