Algorithm for grouping anagram words

前端 未结 14 1553
悲&欢浪女
悲&欢浪女 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-07 23:52

    You will need large integers (or a bit vector actually) but the following might work

    the first occurrence of each letter get's assigned the bit number for that letter, the second occurence gets the bit number for that letter + 26.

    For example

    a #1 = 1 b #1 = 2 c #1 = 4 a #2 = 2^26 b #2 = 2 ^ 27

    You can then sum these together, to get a unique value for the word based on it's letters.

    Your storage requirements for the word values will be:

    n * 26 bits

    where n is the maximum number of occurrences of any repeated letter.

提交回复
热议问题