1、题目:字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
2、解答
# 排序法
def groupAnagrams(self, strs):
"""
使用排序后的单词作为key来保存这整个数组
:type strs: List[str] ["eat", "tea", "tan", "ate", "nat", "bat"]
:rtype: List[List[str]] [
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
"""
result = {}
for word in strs:
sort_word = "".join(sorted(word))
tmp = result.get(sort_word, [])
tmp.append(word)
result[sort_word] = tmp
return list(result.values())
def groupAnagrams2(self, strs):
"""
哈希表法
:type strs: List[str] ["eat", "tea", "tan", "ate", "nat", "bat"]
:rtype: List[List[str]] [
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
"""
result = {}
for word in strs:
chars = [0]*26
for char in word:
chars[ord(char)-ord('a')] += 1
key = tuple(chars)
tmp = result.get(key, [])
tmp.append(word)
result[key] = tmp
return list(result.values())
|