Algorithm for grouping anagram words

前端 未结 14 1417
悲&欢浪女
悲&欢浪女 2020-12-07 23:30

Given a set of words, we need to find the anagram words and display each category alone using the best algorithm.

input:

man car kile arc none like
<         


        
相关标签:
14条回答
  • 2020-12-08 00:11

    A Python version for giggles:

    from collections import defaultdict
    res = defaultdict(list)
    L = "car, acr, bat, tab, get, cat".split(", ")
    
    for w in L:
        res["".join(sorted(w))].append(w)
    
    print(res.values())
    
    0 讨论(0)
  • 2020-12-08 00:12

    python code:

    line = "man car kile arc none like"
    hmap = {}
    for w in line.split():
      ws = ''.join(sorted(w))
      try:
        hmap[ws].append(w)
      except KeyError:
        hmap[ws] = [w]
    
    for i in hmap:
       print hmap[i]
    

    output:

    ['car', 'arc']
    ['kile', 'like']
    ['none']
    ['man']
    
    0 讨论(0)
提交回复
热议问题