我想使用Go对具有相同组合的字符串进行分组。假设我有这样的字符串数组:['kita', 'atik', 'tika', 'aku', 'kia', 'makan', 'kua']预期的输出是这样的[ ["kita", "atik", "tika"], ["aku", "kua"], ["makan"], ["kia"]]
1 回答
至尊宝的传说
TA贡献1789条经验 获得超10个赞
这应该是使用地图实现的:
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)
}
- 1 回答
- 0 关注
- 123 浏览
添加回答
举报
0/150
提交
取消