class Trie { public class TrieNode{ boolean isWord; TrieNode[] letters = new TrieNode[26]; }
TrieNode root ; public Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ public void insert(String word) { if (word != null) { char[] chars = word.toCharArray(); TrieNode tmp = root; for (int i = 0; i < chars.length; i++) { if(tmp.letters[chars[i]-'a'] == null) tmp.letters[chars[i]-'a'] = new TrieNode(); tmp = tmp.letters[chars[i]-'a']; } tmp.isWord = true; } }
/** Returns if the word is in the trie. */ public boolean search(String word) { if (word != null) { char[] chars = word.toCharArray(); TrieNode tmp = root; for (int i = 0; i < chars.length; i++) { if (tmp.letters[chars[i]-'a'] == null) return false; tmp = tmp.letters[chars[i]-'a']; } return tmp.isWord; } return false; }
/** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { char[] chars = prefix.toCharArray(); TrieNode tmp = root; for (int i = 0; i < chars.length; i++) { if (tmp.letters[chars[i]-'a'] == null) return false; tmp = tmp.letters[chars[i]-'a']; } return true; } }
近期评论