java - Get Words out of a Trie Data Structure -
i have following trie data structure:
public class cdictionary implements idictionary { private static final int n = 'z' -'a'+1; private static class node { private boolean end = false; private node[] next = new node[n]; } private int size = 0; private node root = new node(); @override public boolean contains(string word) { node node = this.contains(root,word,0); if (node == null) { return false; } return node.end; } private node contains(node node, string str, int d) { if (node == null) return null; if (d == str.length()) return node; char c = str.charat(d); return contains(node.next[c-'a'], str, d+1); } @override public void insert(string word) { this.root = insert(this.root, word, 0); this.size++; } private node insert(node node, string str, int d) { if (node == null) node = new node(); if (d == str.length()) { node.end = true; return node; } char c = str.charat(d); node.next[c-'a'] = this.insert(node.next[c-'a'], str, d+1); return node; } @override public int size() { return size; }
the trie filled words like
for, the, each, home, is, it, egg, red...
now need function words specific length example length 3
public list<string> getwords(int lenght) { }
with words mentioned above should return list words
for,the,egg,red
the problem how can restore these words out of trie structur?
you need recurse through structure maximum depth of n (in case 3)
you adding couple of methods dictionary...
public list<string> findwordsoflength(int length) { // create new empty list results list<string> results = new arraylist<>(); // start @ root node (level 0)... findwordsoflength(root, "", 0, length, results); // return results return results; } public void findwordsoflength(node node, string wordsofar, int depth, int maxdepth, list<string> results) { // go through each "child" of node for(int k = 0; k < node.next.length; k++) { node child = node.next[k]; // if child exists... if(child != null) { // work out letter child represents char letter = 'a' + k; // if have reached "maxdepth" letters... if(depth == maxdepth) { // add letter end of word far , add word results list results.add(wordsofar + letter); } else { // otherwise recurse next level findwordsoflength(child, wordsodar + letter, depth + 1, maxdepth, results); } } } }
(i have not compiled / tested this, should give idea of need do)
hope helps.
Comments
Post a Comment