题目
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
总结
看到这种题,首先就想使用唯一的一个map来表示同一类型的字符串。
但是在python中不能使用map作为map中的key,也就是map不可散列,这样就只能通过比较两个map是否相同来区分。
代码:
class Solution:
def groupAnagrams(self, strs: 'List[str]') -> 'List[List[str]]':
result = []
maps = []
for s in strs:
added = False
map_s = {}
for c in s:
if c in map_s:
map_s[c] += 1
else:
map_s[c] = 1
for i, map in enumerate(maps):
if len(map_s) == len(map):
is_same = True
for k,v in map.items():
if k not in map_s or map_s[k] != v:
is_same = False
break
if is_same:
result[i].append(s)
added = True
break
if not added:
result.append([s])
maps.append(map_s)
return result
但是,在这题中,一个字符串只可能有26个字母构成。可以使用一个元组来表示一个map(k1,k2,…,k26),这样就可以使用String来完成映射,去除了比较的时间。
代码:
class Solution:
def groupAnagrams(self, strs: 'List[str]') -> 'List[List[str]]':
result = {}
for s in strs:
map_s = [0] * 26
for c in s:
map_s[ord(c) - 97] += 1
map_s = tuple(map_s)
if map_s in result:
result[map_s].append(s)
else:
result[map_s] = [s]
return list(result.values())
如果不确定构成的字符种类或种类过多,可以对字符进行排序,使用排序后的字符串作为key。
本文探讨了在给定字符串数组中,如何高效地将字谜(anagram)字符串进行分组的问题。通过对比两种方法——使用字典(map)和利用元组表示字母频率,展示了如何避免不必要的比较操作,从而显著提高算法效率。
480

被折叠的 条评论
为什么被折叠?



