45 lines
925 B
Go
45 lines
925 B
Go
//go:build !solution
|
|
|
|
package spacecollapse
|
|
|
|
import (
|
|
"strings"
|
|
"unicode"
|
|
)
|
|
|
|
// 1 alloc/op, best ns/op but more iterations overall
|
|
func CollapseSpaces(input string) string {
|
|
output := strings.Builder{}
|
|
output.Grow(len(input))
|
|
writeSpace := true
|
|
for _, r := range input {
|
|
if unicode.IsSpace(r) {
|
|
if writeSpace {
|
|
output.WriteRune(' ')
|
|
}
|
|
writeSpace = false
|
|
} else {
|
|
output.WriteRune(r)
|
|
writeSpace = true
|
|
}
|
|
}
|
|
return output.String()
|
|
}
|
|
|
|
// 3 allocs/op for runes slice, output slice and output string
|
|
// func CollapseSpaces(input string) string {
|
|
// runes := []rune(input)
|
|
// output, writeSpace := make([]rune, 0, len(runes)), true
|
|
// for _, r := range input {
|
|
// if unicode.IsSpace(r) {
|
|
// if writeSpace {
|
|
// output = append(output, ' ')
|
|
// }
|
|
// writeSpace = false
|
|
// } else {
|
|
// output = append(output, r)
|
|
// writeSpace = true
|
|
// }
|
|
// }
|
|
// return string(output)
|
|
// }
|