'''
leetcode 49. 字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
算法1: 根据字典序排序后相同的两个字符串是字母异位词
将字符串数组中的每个字符串进行排序,排序后相同的字符串被分到相同的组别
算法在输入规模较大的情况下超时
算法2:对于字符串列表中的每个字符串,统计小写字母字符出现的个数,即为每个字符串统计哈希表
哈希表相同的字符串是字母异位词,这样的好处是不用对字符串排序
'''
class Solution:
def groupAnagrams(self, strs):
if len(strs)<=1:
return [strs]
result=[]
temp={} # 字典,键表示字符串的哈希表(列表结构),值是列表,表示哈希表相同的字符串的集合
for string in strs:
temp_item=[0 for _ in range(26)]# 当前字符串的哈希表
for c in string:
temp_item[ord(c)-ord('a')]+=1
# print(temp_item,string)
if tuple(temp_item) in temp:
temp[tuple(temp_item)].append(string)
else:
temp[tuple(temp_item)]=[string]
for k,v in temp.items():
result.append(v)
return result
if __name__=="__main__":
print(Solution().groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))