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--
	}
}
相关推荐
.柒宇.5 小时前
力扣hot100----15.三数之和(java版)
java·数据结构·算法·leetcode
雪域迷影6 小时前
Go语言中通过get请求获取api.open-meteo.com网站的天气数据
开发语言·后端·http·golang·get
程序员阿鹏9 小时前
56.合并区间
java·数据结构·算法·leetcode
数据知道9 小时前
Go语言设计模式:适配器模式详解
设计模式·golang·建造者模式
Brookty12 小时前
【算法】位运算| & ^ ~ -n n-1
学习·算法·leetcode·位运算
剪一朵云爱着13 小时前
力扣2560. 打家劫舍 IV
算法·leetcode
ZHE|张恒19 小时前
LeetCode - 寻找两个正序数组的中位数
算法·leetcode
努力学算法的蒟蒻19 小时前
day03(11.1)——leetcode面试经典150
java·算法·leetcode