哈喽!大家好,很高兴又见面了,我是编程网的一名作者,今天由我给大家带来一篇《按给定切片对切片字符串进行排序/排序》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
问题内容如何按照另一字符串片段给出的顺序对字符串片段进行排序。如果输入切片中不存在该字符串,则忽略它。
animalsInput := []string{"cat", "bird", "zebra", "fox"}
animalsOrder := []string{"bird", "lion", "fox"}
//desired output
//{"bird", "fox", "cat", "zebra"}
解决方案
实现此目的的一种方法是根据顺序数组编写 rank
映射
rank:=map[string]int{}
for i, x:=range animalsorder {
rank[x]=i
}
然后在sort
中使用rank
:
sort.slice(animalsinput,func(i,j int) bool {
irank, ok:=rank[animalsinput[i]]
if !ok {
irank=len(animalsinput)
}
jrank, ok:=rank[animalsinput[j]]
if !ok {
jrank=len(animalsinput)
}
return irank<jrank
})
您可以尝试以下代码:
package main
import (
"fmt"
)
func sort(in, order []string) (out []string) {
flag := make([]bool, len(in))
out = make([]string, len(in))
orderCountMap := make(map[string]int)
for i := range in {
orderCountMap[in[i]] += 1
}
for i := range in {
if _, found := orderCountMap[in[i]]; found {
flag[i] = true
} else {
flag[i] = false
}
}
p := 0
for i := range order {
if v, found := orderCountMap[order[i]]; found {
for j := 0; j < v; j++ {
out[p] = order[i]
p += 1
}
}
}
for i := range flag {
if !flag[i] {
out[p] = in[i]
p += 1
}
}
return
}
func main(){
animalsInput := []string{"cat", "bird", "zebra", "fox"}
animalsOrder := []string{"bird", "lion", "fox", "zebra", "cat"}
out := sort(animalsInput, animalsOrder)
fmt.Println(out)
}
本篇关于《按给定切片对切片字符串进行排序/排序》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注编程网公众号!