class Trie { private TreeNode root; public static class TreeNode{ private char data; private TreeNode[] child = new TreeNode[26]; private boolean isEndingChar = false; public TreeNode(char data){ this.data = data; } } /** Initialize your data structure here. */ public Trie() { root = new TreeNode('/'); } /** Inserts a word into the trie. */ public void insert(String word) { TreeNode node = root; char[] array = word.toCharArray(); for(int i = 0 ; i < array.length ; i++){ int index = array[i] - 'a'; if(node.child[index] == null){ node.child[index] = new TreeNode(array[i]); } node = node.child[index]; } node.isEndingChar = true; } /** Returns if the word is in the trie. */ public boolean search(String word) { TreeNode node = root; char[] array = word.toCharArray(); for(int i = 0 ; i < array.length ; i++){ int index = array[i] - 'a'; if(node.child[index] == null){ return false; } node = node.child[index]; } if(!node.isEndingChar){ return false; } return true; } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { TreeNode node = root; char[] array = prefix.toCharArray(); for(int i = 0 ; i < array.length ; i++){ int index = array[i] - 'a'; if(node.child[index] == null){ return false; } node = node.child[index]; } return true; } }
/** * 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); */