/** Initialize your data structure here. */ public Trie() { this.root = new TrieNode(' '); }
/** Inserts a word into the trie. */ public void insert(String word) { TrieNode node = root; for (int i=0; i<word.length(); i++) { char cur = word.charAt(i); if (null == node.children[cur - 'a']) { node.children[cur - 'a'] = new TrieNode(cur); } node = node.children[cur - 'a']; } node.end = '#'; }
/** Returns if the word is in the trie. */ public boolean search(String word) { TrieNode node = root; for (int i=0; i<word.length(); i++) { char ch = word.charAt(i); if (node.children[ch - 'a'] == null) return false; node = node.children[ch - 'a']; } return node.end == '#'; }
/** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { TrieNode node = root; for (int i=0; i<prefix.length(); i++) { char ch = prefix.charAt(i); if (null == node.children[ch - 'a']) return false;