当前位置:   article > 正文

Golang | Leetcode Golang题解之第151题反转字符串中的单词

Golang | Leetcode Golang题解之第151题反转字符串中的单词

题目:

题解:

  1. import (
  2. "fmt"
  3. )
  4. func reverseWords(s string) string {
  5. //1.使用双指针删除冗余的空格
  6. slowIndex, fastIndex := 0, 0
  7. b := []byte(s)
  8. //删除头部冗余空格
  9. for len(b) > 0 && fastIndex < len(b) && b[fastIndex] == ' ' {
  10. fastIndex++
  11. }
  12. //删除单词间冗余空格
  13. for ; fastIndex < len(b); fastIndex++ {
  14. if fastIndex-1 > 0 && b[fastIndex-1] == b[fastIndex] && b[fastIndex] == ' ' {
  15. continue
  16. }
  17. b[slowIndex] = b[fastIndex]
  18. slowIndex++
  19. }
  20. //删除尾部冗余空格
  21. if slowIndex-1 > 0 && b[slowIndex-1] == ' ' {
  22. b = b[:slowIndex-1]
  23. } else {
  24. b = b[:slowIndex]
  25. }
  26. //2.反转整个字符串
  27. reverse(&b, 0, len(b)-1)
  28. //3.反转单个单词 i单词开始位置,j单词结束位置
  29. i := 0
  30. for i < len(b) {
  31. j := i
  32. for ; j < len(b) && b[j] != ' '; j++ {
  33. }
  34. reverse(&b, i, j-1)
  35. i = j
  36. i++
  37. }
  38. return string(b)
  39. }
  40. func reverse(b *[]byte, left, right int) {
  41. for left < right {
  42. (*b)[left], (*b)[right] = (*b)[right], (*b)[left]
  43. left++
  44. right--
  45. }
  46. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/726676
推荐阅读
相关标签
  

闽ICP备14008679号