Algorithm Question about finding all valid words in a dictionary

Based on the dictionary (list of strings only).

You receive a feed of an unknown number of letters from an external source. Given the sequence of letters, how would you list all valid words (from diciontary) that you can make from any combination of these letters.

So if you get: abpplead

You should find apple, bad, pad, lead, etc.

I do not know a better answer. But what are some reasonably efficient ways to do this, which data structures to use, etc.

Also, suppose you can pre-process the input so that you can save the input letters when they enter any data structure you want.

+3
source share
6 answers

Put the dictionary in trie. Then put the letters in an array of counters, indexed by their character values, maintaining counts for each letter (let this counter []). Then do the first search order trie in depth, decreasing the counts [letter] for each letter as you go down and increasing it on the way back. Now that the counter [letter] is about to go negative, stop and go back up. Each time you reach the word terminator, output the result.

+5
source

- , " ": , , (.. , . , , ). O (N) N .

( , , , ), "", 26 , ( , - ). , , , . O (N) HashMap.

, K, ; (O (2 ^ K) ). Z O (N + Z * 2 ^ K) (vs O (Z * N) ), ( , O() ), N > 2 ^ .

+2

, .
, , dict x[letter: amount], , :

for each word 'w' in dictionary
    init x from given letters

    for each letter `ch` in word `w` 
        --x[ch]
        if x[ch] < 0
            break, do not add w to result

    result.add(w)
+1

1. . , . - a-z, a-z - , .. - .

, , , , ..

, , , .

0

dawg, dawg- . ruby ​​ dawg ; , oamaml (unreleased), , . , .

0

Use the rete algorithm and treat the problem as a problem in a rule-based domain. Words are rules (with their own letters as rule patterns). For each given set of letters, you apply a rule base, and all words that match will “shoot”. Rinse and repeat. :)

[Edit ps]

The motivation here is: "Rete performance is theoretically independent of the number of rules [words in the dictionary in your case] in the system."

-1
source

Source: https://habr.com/ru/post/1721462/


All Articles