Golang:map的比较

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

map can only be compared to nil

Golang:map的比较_第1张图片

查看文档发现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

你可能感兴趣的:(Golang)