49-Group Anagrams-(Medium) 题解

1、题目

  

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note: All inputs will be in lower-case.

2、分析,该题目可以针对每个字符串进行排序,然后计算每个字符串的hash值进行归类

 

3、优化、在计算hash值的时候,考虑hash算法跟字符串排序无关,也就是不用进行排序,针对26个字母分配26个质数,然后将hash函数设置为每个字母映射的质数乘积,便不用进行排序了,该方法利用了质数的特性

  两个质数相乘得到一个合数,这个合数不会分解为其它质数的乘积

 

4、代码:

  

 1 #!/usr/local/bin/python3
 2 # -*- coding: utf-8 -*-
 3 __author__ = 'qqvipfunction'
 4 
 5 
 6 primeTable = [2,3,5,7,11, 13,17,19,23,29, 31,37,41,43,47, 53,59,61,67,71, 73,79,83,89,97, 101]
 7 
 8 class Solution(object):
 9 
10     def groupAnagrams(self, strs):
11         """
12         :type strs: List[str]
13         :rtype: List[List[str]]
14         """
15         map = {}
16         for i in range(0 , len(strs)):
17             str = strs[i]
18             hash = self.hash_str(str)
19             list = map.get(hash, None)
20             if not list:
21                 list = []
22             list.append(str)
23             map[hash] = list
24 
25         return map.values()
26 
27     def hash_str(self, str):
28         length = len(str)
29         charAvalue = ord('a')
30         if length > 0:
31             hashSum = 1
32             for i in range(0, length):
33                 hashSum = hashSum * primeTable[(ord(str[i]) - charAvalue)]
34             return hashSum
35         return 0
36 
37 
38 
39 if __name__ == '__main__':
40     s = Solution()
41     print(s.groupAnagrams(["eat", "tea", "bat"]))

 

posted @ 2017-02-23 21:05  兜兜有糖的博客  阅读(464)  评论(0编辑  收藏  举报