49. Group Anagrams

Given an array of strings, group anagrams together.

Example:

1
2
3
4
5
6
7
8
> Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
> Output:
> [
> ["ate","eat","tea"],
> ["nat","tan"],
> ["bat"]
> ]
>

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.
  1. sorted(String):

    return a sorted list of String

    EX: sorted('tae') —> return ['a', 'e', 't']

  2. 如果要反复访问,用map,比用list 遍历要快得多

  3. list(dic.values())

RES

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
mapp = {}
for s in strs:
temp = ''.join(sorted(s))
if temp not in mapp:
mapp[temp] = [s]
else:
mapp[temp].append(s)
return list(mapp.values())