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 spacecollapse
|
2020-02-24 19:54:48 +00:00
|
|
|
|
2024-06-03 01:29:30 +00:00
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
"unicode"
|
|
|
|
)
|
|
|
|
|
|
|
|
// 1 alloc/op, best ns/op but more iterations overall
|
2020-02-24 19:54:48 +00:00
|
|
|
func CollapseSpaces(input string) string {
|
2024-06-03 01:29:30 +00:00
|
|
|
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()
|
2020-02-24 19:54:48 +00:00
|
|
|
}
|
2024-06-03 01:29:30 +00:00
|
|
|
|
|
|
|
// 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)
|
|
|
|
// }
|