Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
这个问题,我的思路是用哈希表来解决,分别对s和t遍历一次,遍历s的时候,用字母当关键字,统计字母出现的次数,第二次遍历的时候,每遍历到一个字母就让这个字母的计数减一,这样就能做判断了
题目中提到了unicode的问题,在go语言中可以轻松处理,在对字符串使用for range语句的时候,提取出来的value不是byte类型而是rune类型的,一个rune就能对应一个unicode码
func isAnagram(s string, t string) bool { if (len(s) != len(t)) { return false } m := map[string]int{} for _, v := range s { key, ok := m[string(v)] if !ok { m[string(v)] = 1 } else { m[string(v)] = key + 1 } } for _, v := range t { key, ok := m[string(v)] if !ok { return false } if key == 0 { return false } m[string(v)] = key - 1 } return true }
有疑问加站长微信联系(非本文作者)