问题:

反转字符串

  1. "123456789" ==> "987654321"
  2. "the sky is blue" ==> "blue is sky the"

代码示例:

package main

import "fmt"

func main() {

    str1 := "123456789"
    str2 := "the sky is blue"
    fmt.Println(reversalStr1(str1))
    fmt.Println(reversalStr2(str2))

}

func reversalStr1(str string) string {
    bytes := []byte(str)
    i := 0
    j := len(bytes) - 1
    for i < j {
        bytes[i], bytes[j] = bytes[j], bytes[i]
        i++
        j--
    }
    return string(bytes)
}

func reversalStr2(str string) string {
    bytes := []byte(str)
    i := 0
    j := len(bytes) - 1
    for i < j {
        bytes[i], bytes[j] = bytes[j], bytes[i]
        i++
        j--
    }

    begin := 0
    for k, v := range bytes {
        if v == ' ' || k == len(bytes) - 1 {
            end := k - 1
            if k == len(bytes) - 1 {
                end = k
            }
            for begin < end {
                bytes[begin], bytes[end] = bytes[end], bytes[begin]
                begin++
                end--
            }
            begin = k + 1
        }
    }

    return string(bytes)
}