Golang:map的比较

假如想象 提交于 2020-03-12 08:45:37

在提交Leetcode 242. 有效的字母异位词代码时碰到了如下编译错误:

map can only be compared to nil

image.png

查看文档发现Golang中要比较两个map实例需要使用reflect包的DeepEqual()方法。如果相比较的两个map满足以下条件,方法返回true:

Map values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they are the same map object or their corresponding keys (matched using Go equality) map to deeply equal values.

1.两个map都为nil或者都不为nil,并且长度要相等
they are both nil or both non-nil, they have the same length
2.相同的map对象或者所有key要对应相同
either they are the same map object or their corresponding keys
3.map对应的value也要深度相等
map to deeply equal values

题目提交改为以下即可。

func isAnagram(s string, t string) bool {
    sDir := map[string]int{}
    tDir := map[string]int{}
    for _,ss:= range s {
        sDir[string(ss)]++
    }
    for _,tt:= range t {
        tDir[string(tt)]++
    }
    return reflect.DeepEqual(sDir,tDir)
}

参考:

https://golang.org/pkg/reflect/#DeepEqual

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!