dougeqiang1619
2019-06-05 19:25
浏览 103
已采纳

通过在golang中使用for循环来反转字符串效率低下?

I did it like this Golang:

func reverseStr(str string) string {
    var reversed string

    for i := len(str) - 1; i >= 0; i-- {
        reversed += string(str[i])
    }

    return reversed
}

I'm a beginner and can't do better for now, but I'm still learning. I'd like to know is my method less efficient than the ones I saw online that use runes:

func reverse(s string) string {
    chars := []rune(s)
    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
        chars[i], chars[j] = chars[j], chars[i]
    }
    return string(chars)
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题