leetcode49

Description

Given an array of strings, group anagrams together.

Example:

1
2
3
4
5
6
7
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.

Idea

You can sort str “ate”,”eat”,”tea” into “aet”, “aet”, “aet”, then they will share the same key, which bring the hashmap into your mind.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dic = {}

for s in strs:
sorted_key = ''.join(sorted(s))
if sorted_key not in dic:
dic[sorted_key] = []
dic[sorted_key].append(s)

return list(dic.values())

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# sorted examples
# vowels list
pyList = ['e', 'a', 'u', 'o', 'i']
print(sorted(pyList))

# string
pyString = 'Python'
print(sorted(pyString))

# vowels tuple
pyTuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(pyTuple))

# results
['a', 'e', 'i', 'o', 'u']
['P', 'h', 'n', 'o', 't', 'y']
['a', 'e', 'i', 'o', 'u']