2022-02-10 22:06:57 +00:00
|
|
|
//go:build !solution
|
2020-02-24 19:54:48 +00:00
|
|
|
|
2020-02-26 20:26:57 +00:00
|
|
|
package reverse
|
2020-02-24 19:54:48 +00:00
|
|
|
|
2024-06-03 01:29:30 +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 {
|
2024-06-03 01:29:30 +00:00
|
|
|
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
|
|
|
}
|