卖萌的弱渣

I am stupid, I am hungry.

Group Anagrams

Given an array of strings, group anagrams together.

For example,

given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”], Return:

1
2
3
4
5
[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

All inputs will be in lower-case.

Solution

  • hash_map:<strs[i], 和strs[i] 互为anagrams的其他字符串组成的列表>
(Group-Anagrams.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """

        ret = []
        # hash_map: <strs[i], 和strs[i]互为anagrams的其他字符串>
        hash_map = dict()
        for i , s in enumerate(strs):
            target = "".join(sorted(s))
            if target not in hash_map:
                hash_map[target] = [s]
            else:
                hash_map[target].append(s)

        for l in hash_map.values():
            # l 就是所有anagrams的列表
            ret.append(sorted(l))

        return ret