leetcode - hash table 49. Group Anagrams

topic

Given an array of strings, group anagrams together.

Example:

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.

 

Knowledge Point

There are two methods of non-violence [violent methods, when the word strs more certainly not. Violence because time complexity is O (N ^ 2)]. Here used collections this package.

a container collections, which has a defaultdict () object that can initialize a dictionary. Different from the ordinary dictionary, for the key not yet initialized, the dictionary can () is passed the key to set the initial value of the type according to defaultdict.

eg: ordinary dictionary written so, because no "key" initialization error

# 普通 dictionary:
dic_norm = {}
dic_norm["key"] = 1

But collections.defaultdict so write ok

# collections default dictionary
import collections
dict_collections = collections.defaultdict(int)  # 这里设置成int还是list等其他数据类型,看需要
dict_collections["key"] = 2

# 设置初始值
dict_collections = collections.defaultdict(lambda: 0) 
dict_collections = collections.defaultdict(lambda: [1])

 

answer

method one:

import collections
class Solution:
    def groupAnagrams(self, strs):
        ans = collections.defaultdict(list)
        for word in strs:
            count = [0]*26
            for c in word:
                count[ord(c) - ord('a')] +=1   # ord 函数返回字符的asic码
            ans[tuple(count)].append(word)
        
        return ans.values()  # collections.defaultdict和普通的dict一样,.values()函数范围value组成的list

Method Two:

import collections
class Solution:
    def groupAnagrams(self, strs):
        ans = collections.defaultdict(list)
        for word in strs:
            ans[tuple(sorted(word))].append(word)
        return ans.values()

Starting with a violent writing, the results of a time out, or to see the answer, a rise of knowledge

Published 45 original articles · won praise 1 · views 3380

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104453900