Algorithm for grouping anagram words

前端 未结 14 1511
悲&欢浪女
悲&欢浪女 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: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']
    

提交回复
热议问题