2013年12月11日 星期三

[Programming Pearl] 一個問題


Given a dictionary of English words (one word per input line in lower case letters), we must find all anagram classes.

不禁令人想到一個 hash function h:

h(A) = 2, h(B) = 3, h(C) = 5, h(D) = 7, h(E) = 11, ..., h(k-th alphabet) = k-th prime number.

h is multiplicative on each alphabet.  For example, h(WORD) = h(W) h(O) h(R) h(D).   Observe that x and y are in the same anagram class if and only if h(x) = h(y).

Or you can define h to be h(letter[]) = sort(letter[]).

沒有留言:

張貼留言