Given a dictionary and a list of letters find all valid words that can be built with the letters

前端 未结 12 845
闹比i
闹比i 2021-01-31 12:26

The brute force way can solve the problem in O(n!), basically calculating all the permutations and checking the results in a dictionary. I am looking for ways to improve the com

12条回答
  •  囚心锁ツ
    2021-01-31 12:31

    1. "Sign" the letters available by sorting them in order; that's O(m log m), where m is the number of letters.

    2. "Sign" each word in the dictionary by sorting the letters of the word in order; that's O(k log k), where k is the length of the word.

    3. Compare the letter signature to each word signature; that's O(min(m, k) * n), where n is the number of words in the dictionary. Output any word that matches.

    Assuming an English word list of approximately a quarter-million words, and no more than about half a dozen, that should be nearly instantaneous.

提交回复
热议问题