public boolean isWord(String prefix) { return myPrefixTrie.isWord(prefix); }
private boolean add(String s, int index) { if (index == s.length()) { if (isWord) { return false; } isWord = true; return true; } char c = s.charAt(index); for (int i = 0; i < numChildren; i++) { if (child[i].ch == c) { return child[i].add(s, index + 1); } } // this code adds from the bottom to the top because the addChild method // checks for cyclic references. This prevents quadratic runtime. int i = s.length() - 1; Trie t = createNode(s.charAt(i--)); t.isWord = true; while (i >= index) { Trie n = createNode(s.charAt(i--)); n.addChild(t); t = n; } addChild(t); return true; }
/** * Removes the specified string from the trie. Returns true if the string was removed or false if * the string was not a word in the trie. * * @param s String. * @return true or false. */ public boolean remove(String s) { Trie t = getNode(s); if ((t == null) || !t.isWord) { return false; } t.isWord = false; while ((t != null) && (t.numChildren == 0) && !t.isWord) { Trie p = t.parent; if (p != null) { p.removeChild(t); } t = p; } return true; }
/** * Removes all words from the trie that begin with the specified prefix. Returns true if the trie * contained the prefix, false otherwise. * * @param prefix String. * @return true or false. */ public boolean removeAll(String prefix) { Trie t = getNode(prefix); if (t == null) { return false; } if (t.parent == null) { if ((t.numChildren == 0) && !t.isWord) { return false; } for (int i = 0; i < t.numChildren; i++) { t.child[i].parent = null; t.child[i] = null; } t.numChildren = 0; t.isWord = false; return true; } Trie p = t.parent; p.removeChild(t); t = p; while ((t != null) && (t.numChildren == 0) && !t.isWord) { p = t.parent; if (p != null) { p.removeChild(t); } t = p; } return true; }