Topic: 49. Grouping of Alphabetical Anagrams
Link: https://leetcode-cn.com/problems/group-anagrams/description/
The title description is very clear.
Given an array of strings, group anagrams together. Alphabetical anagrams are strings of the same letters but different arrangements.
Example:
input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
illustrate:
- All input is lowercase.
- The order in which the answers are output is not considered.
I don't know the correct solution, I wrote it blindly.
python:
import collections def getCntRet(s): ret = [] for (key,val) in (collections.Counter(s)).items(): ret.append(str(key)+str(val)) output="" for item in sorted(ret): output+=item return output class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ dic=dict() for item in strs: temp = getCntRet(item) # for i in range(len(item)): # temp|=(1<<(ord(item[i])-ord("a"))) if str(temp) in dic: dic[str(temp)].append(item) else: dic[str(temp)]=[] dic[str(temp)].append(item) ret = [] for (key,val) in dic.items(): ret.append(val) return right