shad-go/utf8/reverse/reverse.go

34 lines
769 B
Go
Raw Normal View History

2022-02-10 22:06:57 +00:00
//go:build !solution
2020-02-24 19:54:48 +00:00
package reverse
2020-02-24 19:54:48 +00:00
import (
"strings"
"unicode/utf8"
)
// inplace []rune reverse with 2 allocations
// first for runes slice and second for output
// func Reverse(input string) string {
// runes := []rune(input)
// for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
// runes[i], runes[j] = runes[j], runes[i]
// }
// return string(runes)
// }
// string.Builder and utf8 decoding magic = 1 allocation
// overall more iterations but each one is faster,
// so its as fast as the inplace []rune reverse
2020-02-24 19:54:48 +00:00
func Reverse(input string) string {
output := strings.Builder{}
output.Grow(len(input))
end := len(input)
for end > 0 {
r, n := utf8.DecodeLastRuneInString(input[:end])
end -= n
output.WriteRune(r)
}
return output.String()
2020-02-24 19:54:48 +00:00
}