猿问

如何找到两片字符串之间的差异

这是我想要的结果


slice1 := []string{"foo", "bar","hello"}

slice2 := []string{"foo", "bar"}


difference(slice1, slice2)

=> ["hello"]

我正在寻找两个字符串切片之间的区别!


叮当猫咪
浏览 198回答 3
3回答

肥皂起泡泡

假设 Go 映射是 ~O(1),这里是一个 ~O(n) 差异函数,适用于未排序的切片。// difference returns the elements in `a` that aren't in `b`.func difference(a, b []string) []string {    mb := make(map[string]struct{}, len(b))    for _, x := range b {        mb[x] = struct{}{}    }    var diff []string    for _, x := range a {        if _, found := mb[x]; !found {            diff = append(diff, x)        }    }    return diff}
随时随地看视频慕课网APP

相关分类

Go
我要回答