208. Implement Trie (Prefix Tree)
创一个root node, 不用什么值, TrieNode要有一个26到数组记录每个字母存不存在,再来一个isWord给每个node判断一下是不是一个word(单词最后一个node才是一个word)
1 class Trie { 2 class TrieNode{ 3 boolean isWord; 4 TrieNode[] children = new TrieNode[26]; 5 6 } 7 TrieNode root = new TrieNode(); 8 9 /** Initialize your data structure here. */ 10 public Trie() { 11 12 } 13 14 /** Inserts a word into the trie. */ 15 public void insert(String word) { 16 TrieNode node = root; 17 for(int i = 0; i < word.length(); i++){ 18 char c = word.charAt(i); 19 if(node.children[c - 'a'] != null){ 20 node = node.children[c - 'a']; 21 }else{ 22 node.children[c - 'a'] = new TrieNode(); 23 node = node.children[c - 'a']; 24 } 25 } 26 node.isWord = true; 27 28 } 29 30 /** Returns if the word is in the trie. */ 31 public boolean search(String word) { 32 TrieNode node = root; 33 for(int i = 0; i < word.length(); i++){ 34 char c = word.charAt(i); 35 if(node.children[c - 'a'] == null){ 36 return false; 37 }else{ 38 node = node.children[c - 'a']; 39 } 40 41 } 42 return node.isWord; 43 44 } 45 46 /** Returns if there is any word in the trie that starts with the given prefix. */ 47 public boolean startsWith(String prefix) { 48 TrieNode node = root; 49 for(int i = 0; i < prefix.length(); i++){ 50 char c = prefix.charAt(i); 51 if(node.children[c - 'a'] == null){ 52 return false; 53 }else{ 54 node = node.children[c - 'a']; 55 } 56 57 } 58 return true; 59 60 } 61 }