golang - reverse reverse the string

 reverse reverse, it is a basis for comparison algorithms. To implement this method, from common sense considerations may apply a new space, and then sequentially from the tail to the head to fill the space of the string, the final contents of the new space is the result of reversed, this embodiment of the complexity of the algorithm is O (n ), and also you need to re-apply for space .

 However, before and after the character string by reversed-implemented method is very elegant, it dropped to about complexity O (n / 2). Golang language simulation with the following:

package main
 
import (
    "fmt"
)
 
func main() {
    s := "hello,golang语言"
    fmt.Println(reverseString(s))
    fmt.Println(reverseString(reverseString(s)))
    // output: 言语gnalog,olleh
    // output: hello,golang语言
}
 
// 反转字符串
func reverseString(s string) string {
    runes := []rune(s)
    for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
        runes[from], runes[to] = runes[to], runes[from]
    }
    return string(runes)
} 

golang here need to first convert the string into rune string type, then the operation can be reversed.

 

Guess you like

Origin www.cnblogs.com/unqiang/p/12052282.html