get list of anagrams from a dictionary

后端 未结 5 766
生来不讨喜
生来不讨喜 2020-12-01 19:58

Basically, Anagrams are like permutation of string.E.g stack ,sackt ,stakc all are anagrams of stack (thought above words

5条回答
  •  粉色の甜心
    2020-12-01 20:43

    The obvious solution is to map each character to a prime number and multiply the prime numbers. So if 'a'' -> 2 and 'b' -> 3, then

    • 'ab' -> 6
    • 'ba' -> 6
    • 'bab' -> 18
    • 'abba' -> 36
    • 'baba' -> 36

    To minimise the chance of overflow, the smallest primes could be assigned to the more frequent letters (e,t,i,a,n). Note: The 26th prime is 101.

    UPDATE: an implementation can be found here

提交回复
热议问题