在提交Leetcode 242. 有效的字母异位词代码时碰到了如下编译错误:
map can only be compared to nil
查看文档发现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)
}
参考:
来源:CSDN
作者:李小西033
链接:https://blog.csdn.net/lissdy/article/details/104801989