将具有相同组成的字符串分组
Grouping strings with same composition
我想使用 Go 对具有相同组成的字符串进行分组。
假设我有这样的字符串数组:
['kita', 'atik', 'tika', 'aku', 'kia', 'makan', 'kua']
预期的输出是这样的
[
["kita", "atik", "tika"],
["aku", "kua"],
["makan"],
["kia"]
]
这应该可以使用地图来实现:
package main
import (
"log"
"sort"
)
func main() {
words := []string{"kita", "atik", "tika", "aku", "kia", "makan", "kua"}
refs := map[string][]string{}
for _, word := range words {
// normalizing word
r := []rune(word)
sort.Slice(r, func(i, j int) bool { return r[i] < r[j] })
sortedWord := string(r)
// appending in the normalized word map
refs[sortedWord] = append(refs[sortedWord], word)
}
// transforming into a slice of slices
result := [][]string{}
for _, item := range refs {
result = append(result, item)
}
log.Println(result)
}
我想使用 Go 对具有相同组成的字符串进行分组。
假设我有这样的字符串数组:
['kita', 'atik', 'tika', 'aku', 'kia', 'makan', 'kua']
预期的输出是这样的
[
["kita", "atik", "tika"],
["aku", "kua"],
["makan"],
["kia"]
]
这应该可以使用地图来实现:
package main
import (
"log"
"sort"
)
func main() {
words := []string{"kita", "atik", "tika", "aku", "kia", "makan", "kua"}
refs := map[string][]string{}
for _, word := range words {
// normalizing word
r := []rune(word)
sort.Slice(r, func(i, j int) bool { return r[i] < r[j] })
sortedWord := string(r)
// appending in the normalized word map
refs[sortedWord] = append(refs[sortedWord], word)
}
// transforming into a slice of slices
result := [][]string{}
for _, item := range refs {
result = append(result, item)
}
log.Println(result)
}