class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
query = {}
for string in strs:
string_counter = "".join(sorted(string)) # 注意对字符串sort之后会变成 字符list
if string_counter in query:
query[string_counter].append(string)
else:
query[string_counter] = [string]
return [i[1] for i in query.items()]
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagram_dict = collections.defaultdict(list)
for word in strs:
key = ''.join(sorted(word))
anagram_dict[key].append(word)
return list(anagram_dict.values())
class Solution:
def groupStrings(self, strings):
normalized_to_group = collections.defaultdict(list)
for s in strings:
normalized_chars = []
shift = ord(s[0]) - ord('a')
for char in s:
normalized_char_code = ord(char) - shift
if normalized_char_code < ord('a'):
normalized_char_code += 26
normalized_chars.append(chr(normalized_char_code))
normalized_string = ''.join(normalized_chars)
normalized_to_group[normalized_string].append(s)
return list(normalized_to_group.values())