image.png

    1. package main
    2. import (
    3. "fmt"
    4. "strings"
    5. )
    6. func reverseWords(s string) string {
    7. list := strings.Split(s ," ")
    8. var res []string
    9. for i:=len(list)-1;i>=0;i--{
    10. if len(list[i])>0{
    11. res = append(res,list[i])
    12. }
    13. }
    14. s =strings.Join(res," ")
    15. return s
    16. }
    17. func main() {
    18. fmt.Println(reverseWords("the sky is blue"))
    19. fmt.Println(reverseWords(" hello world! "))
    20. }

    image.png

    1. func reverseWords(s string) string {
    2. if s == "" {
    3. return ""
    4. }
    5. res := []byte{}
    6. queue := []string{}
    7. word := []byte{}
    8. for i := 0; i < len(s); i++ {
    9. if s[i] == ' ' {
    10. if len(word) > 0 {
    11. queue = append(queue, string(word))
    12. word = []byte{}
    13. }
    14. } else {
    15. word = append(word, s[i])
    16. }
    17. }
    18. if len(word) > 0 {
    19. queue = append(queue, string(word))
    20. }
    21. if len(queue) <= 0 {
    22. return ""
    23. }
    24. for i := len(queue) - 1; i >= 0; i-- {
    25. res = append(res, []byte(queue[i])...)
    26. res = append(res, ' ')
    27. }
    28. return string(res[:len(res)-1])
    29. }