Group Anagrams
Question
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.
Tags
- String
- Hash Table
Thought
Use the sorted string as the key and the list for anagrams as the value for the dictionary.
Code
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
strDict = {}
for word in strs:
sortWord = ''.join(sorted(word))
if sortWord in strDict:
strDict[sortWord].append(word)
else:
strDict[sortWord] = [word]
return strDict.values()