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

前端 未结 12 872
闹比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:42

    My English is not good so try to understand.

    My approach is using bit/bitwise to increase speed. Still bruteforce, though.

    FIRST STEP

    We only consider distinct character in each word and mark its existence. English has 26 characters, so we need 26 bits. Integer is 32 bits. That's enough.

    Now encode each words in dictionary to an integer number.

    abcffffdffg -> 123444667 -> 123467 (only distinct characters) -> 1111011 (bits) -> 123 (decimal number)
    

    So 2,000,000 words will be converted into 2,000,000 integer numbers.

    Now let say you have this set of letters: a,b,c,d,e

    abcde -> 12345 -> 1111100 (bits)
    

    Do AND operation and we have:

    1111100 (abcde)
    &
    1111011 (abcffffdffg, no e)
    =
    1111000 (result) => result != abcffffdffg => word cannot be created
    

    Other example with a,b,c,d,e,f,g,h:

    11111111 (abcdefgh)
    &
    11110110 (abcffffdffg, no e and h)
    = 
    11110110 (result) => result == abcffffdffg => word can be created
    

    SECOND STEP

    While converting word to number, store the letter count also. If we found a match in first step, we continue to check if the number of letters is enough too.

    Depend on the requirement, you might not need this second step.

    COMPLEXITY

    • O(n) to convert word to number and store letters count. Only need to do this once.
    • O(n) for each search query.

提交回复
热议问题