题目:
题解:
import ("fmt"
)func reverseWords(s string) string {//1.使用双指针删除冗余的空格slowIndex, fastIndex := 0, 0b := []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 := 0for i < len(b) {j := ifor ; j < len(b) && b[j] != ' '; j++ {}reverse(&b, i, j-1)i = ji++}return string(b)
}func reverse(b *[]byte, left, right int) {for left < right {(*b)[left], (*b)[right] = (*b)[right], (*b)[left]left++right--}
}