Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
Problem Solving Ideas:
Reference Baidu Encyclopedia: Trie Tree
The detailed code has been given:
The Java implementation is as follows:
Class Trienode {//Initialize your data structure Here.int num;//How many words are passed through this node, that is, the number of occurrences of the node character trienode[] son;//all sons node Boolean I send;//is not the value of the last node Char val;//node Trienode () {this.num = 1;this.son = new Trienode[26];this.isend = false;}} public class Trie {private Trienode root;public Trie () {root = new Trienode ();} public void Insert (String word) {if (Word = = NULL | | word.length () = = 0) return; Trienode node = this.root;char[] Letters = Word.tochararray (); for (int i = 0; i < word.length (); i++) {Int. POS = Letter S[i]-' a ', if (node.son[pos] = = null) {Node.son[pos] = new Trienode (); node.son[pos].val = Letters[i];} else {Node.son[pos] . num++;} node = Node.son[pos];} Node.isend = true;} Returns If the word is in the Trie.public boolean search (String word) {if (Word = = NULL | | word.length () = = 0) {return false;} Trienode node = root;char[] Letters = Word.tochararray (); for (int i = 0; i < word.length (); i++) {int pos = letters[i] -' a '; if (node.son[pos]! = null) {node = Node.son[pos];} else {return false;}} return node.isend;} Returns If there is any word in the trie//this starts with the given Prefix.public boolean startsWith (String prefix) { if (prefix = = NULL | | prefix.length () = = 0) {return false;} Trienode node = root;char[] Letters = Prefix.tochararray (); for (int i = 0; i < prefix.length (); i++) {int pos = letters [i]-' a '; if (node.son[pos]! = null) {node = Node.son[pos];} else {return false;}} return true;}} Your Trie object would be instantiated and called as such://Trie Trie = new Trie ();//Trie.insert ("somestring");//Trie . Search ("key");
Java for Leetcode 208 Implement Trie (Prefix Tree)