class TrieNode { // Initialize your data structure here. public TrieNode[] next; public boolean isWord; public TrieNode() { next = new TrieNode[256]; isWord = false; } public void addWord() { isWord = true; } }
public class Trie { private TrieNode root;
public Trie() { root = new TrieNode(); }
// Inserts a word into the trie. public void insert(String word) { TrieNode tmp = root; for(int i = 0; i < word.length(); i++) { if(tmp.next[word.charAt(i)] == null) { tmp.next[word.charAt(i)] = new TrieNode(); } tmp = tmp.next[word.charAt(i)]; } tmp.addWord(); }
// Returns if the word is in the trie. public boolean search(String word) { if(word.length() == 0) { return false; } TrieNode tmp = root; int i = 0; while(tmp != null && i != word.length()) { tmp = tmp.next[word.charAt(i)]; i++; } if(i == word.length()) { if(tmp != null && tmp.isWord) { return true; }else { return false; } }else { return false; } }
// Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { if(prefix.length() == 0) { return true; } int i = 0; TrieNode tmp = root; while(tmp != null && i != prefix.length()) { tmp = tmp.next[prefix.charAt(i++)]; } if(tmp == null) { return false; }else { return true; } } }