If I were you, I would change the way you store your dictionary.
Given that the string input contains random letters, what I will do is store all the words in your dictionary in SortedMap<String, char[]> (a TreeMap , to be precise), where the keys are words in your dictionary, and meanings are characters in this word, sorted.
Then I also sorted the characters in the input string and went for it (pseudo code, not tested):
public Set<String> getMatchingWords(final String input) { final char[] contents = input.toCharArray(); Arrays.sort(contents); final int inputLength = contents.length; final Set<String> matchedWords = new HashSet<>(); char[] candidate; int len; int matched; for (final Map.Entry<String, char[]> entry: dictionary.entrySet()) { candidate = entry.getValue();
With trie: it would also be possible; whether this is practical or not, however this is another question, it depends on the size of the dictionary.
But the basic principle will be the same: you will need a sorted array of characters from the dictionary and add little by little to the trie (use the builder).
A trie node will have three elements:
- a map, where the keys are a set of characters that can be mapped as follows, and the values ββare the corresponding trie nodes;
- a set of words that can exactly match a node.
You can use your trie implementation of this if you want.
source share