classTrie { staticclassTrieNode { private TrieNode[] children = newTrieNode[26]; privateboolean isWord; } /** Initialize your data structure here. */ privateTrieNoderoot=newTrieNode();
/** Inserts a word into the trie. */ publicvoidinsert(String word) { TrieNodenode= root; for (char ch : word.toCharArray()) { if (node.children[ch - 'a'] == null) node.children[ch - 'a'] = newTrieNode(); node = node.children[ch - 'a']; } node.isWord = true; }
/** Returns if the word is in the trie. */ publicbooleansearch(String word) { TrieNodenode= root; for (char ch : word.toCharArray()) { if (node.children[ch - 'a'] == null) returnfalse; node = node.children[ch - 'a']; } return node.isWord; }
/** Returns if there is any word in the trie that starts with the given prefix. */ publicbooleanstartsWith(String prefix) { TrieNodenode= root; for (char ch : prefix.toCharArray()) { if (node.children[ch - 'a'] == null) returnfalse; node = node.children[ch - 'a']; } returntrue; } }
/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */