classTrie {TrieNode root; /** Initialize your data structure here. */publicTrie() { root =newTrieNode(); } /** Inserts a word into the trie. */publicvoidinsert(String word) {TrieNode r = root;for (int i =0; i <word.length(); i++) {int pos =word.charAt(i) -'a';if (r.next[pos] ==null) r.next[pos] =newTrieNode(); r =r.next[pos]; }r.isWord=true; } /** Returns if the word is in the trie. */publicbooleansearch(String word) {TrieNode r = root;for (int i =0; i <word.length(); i++) {int pos =word.charAt(i) -'a';if (r.next[pos] ==null) returnfalse; r =r.next[pos]; }returnr.isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */publicbooleanstartsWith(String prefix) {TrieNode r = root;for (int i =0; i <prefix.length(); i++) {int pos =prefix.charAt(i) -'a';if (r.next[pos] ==null) returnfalse; r =r.next[pos]; }// prefix is wordif (r.isWord) returntrue;// iterate next[]for (TrieNode t :r.next) {if (t !=null) returntrue; }returnfalse; }}classTrieNode {TrieNode[] next;boolean isWord;publicTrieNode() { next =newTrieNode[26]; }}