Finding and grouping anagrams by Python

前端 未结 7 1440
無奈伤痛
無奈伤痛 2021-01-20 00:32
input: [\'abc\', \'cab\', \'cafe\', \'face\', \'goo\']
output: [[\'abc\', \'cab\'], [\'cafe\', \'face\'], [\'goo\']]

The problem is simple: it grou

7条回答
  •  深忆病人
    2021-01-20 00:49

    Dave's answer is concise, however the sort which is required by groupby is a O(n log(n)) operation. A faster solution is this:

    from collections import defaultdict
    
    def group_anagrams(strings):
        m = defaultdict(list)
    
        for s in strings:
            m[tuple(sorted(s))].append(s)
    
        return list(m.values())
    

提交回复
热议问题