49. Group Anagrams
Given an array of strings
strs, group the anagrams together. You can return the answer in any order.Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"|"bat"],["nat","tan"],["ate","eat","tea"]]Explanation:
- There is no string in strs that can be rearranged to form
"bat".- The strings
"nat"and"tan"are anagrams as they can be rearranged to form each other.- The strings
"ate","eat", and"tea"are anagrams as they can be rearranged to form each other.Example 2:
Input: strs = [""]
Output: ""Example 3:
Input: strs = ["a"]
Output: "a"
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = {}
finalls = {}
setno = -1
res = []
for word in strs:
if len(word) == 0:
if 'blank' in finalls:
finalls['blank'].append("")
else:
finalls['blank'] = [""]
continue
flag = 0
allsets = []
for ch in word:
if ch not in d:
flag = 1
break
if flag != 1:
for ch in word:
allsets.append(d[ch])
else:
setno += 1
for ch in word:
if ch in d:
d[ch].add(setno)
else:
d[ch] = {setno}
finalls[setno] = [word]
continue
result = set.intersection(*allsets).pop()
if result in finalls:
finalls[result].append(word)
else:
finalls[result] = [word]
for ls in finalls.values():
res.append(ls)
return res