Golang:map的比较

在提交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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容