problem
Given an array of strings, group anagrams together.
solution
这个问题的关键就在于如何判别两个字符串是不是anagrams,比较容易想到的是把字符串排序之后在进行比较,只不过这样的复杂度是O(nlogn),n为字符串长度,
我们要利用的信息就是不管怎么样排列都是anagram,所以要找到一个函数使得变换次序不影响函数值,但是元素不同一定会有不同的函数值。这里我们可以利用加法或乘法的交换律。例如把所有元素对应的数字加起来等,但是这样的函数没有满足第二个条件,也就是可能会有不同的字符串有同样的函数值。
在discussion中看到这样一个hash函数,每一个字符对应一个素数,把所有的字符对应的素数乘起来作为hash值。
肯定满足条件1,下证条件2:
设str1不是str2的anagram,对hash(str1)和hash(str2)进行质因数分解,则对应的分解一定不同,命题得证
from collections import defaultdict
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
d = defaultdict(list)
prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103]
for string in strs:
hashvalue = 1
for ch in string:
hashvalue *= prime[ord(ch) - ord('a')]
d[hashvalue].append(string)
return d.values()
如何找到合适的hash函数