1 class Trie { 2 class TrieNode{ 3 char label; 4 boolean flag; 5 TrieNode[] children; 6 TrieNode(char c){ 7 label = c; 8 flag = false; 9 children = new TrieNode[26]; 10 } 11 TrieNode(){ 12 flag = false; 13 children = new TrieNode[26]; 14 } 15 } 16 TrieNode root; 17 18 /** Initialize your data structure here. */ 19 public Trie() { 20 root = new TrieNode(); 21 22 } 23 24 /** Inserts a word into the trie. */ 25 public void insert(String word) { 26 TrieNode node = root; 27 char[] arr = word.toCharArray(); 28 for(char c : arr){ 29 if(node.children[c-‘a‘] == null){ 30 TrieNode child= new TrieNode(c); 31 node.children[c-‘a‘] = child; 32 node = child; 33 }else{ 34 node = node.children[c-‘a‘]; 35 } 36 } 37 node.flag = true; 38 39 40 } 41 42 /** Returns if the word is in the trie. */ 43 public boolean search(String word) { 44 TrieNode node = root; 45 char[] arr = word.toCharArray(); 46 for(char c : arr){ 47 if(node.children[c-‘a‘] == null){ 48 return false; 49 }else{ 50 node = node.children[c-‘a‘]; 51 } 52 } 53 return node.flag; 54 55 } 56 57 /** Returns if there is any word in the trie that starts with the given prefix. */ 58 public boolean startsWith(String prefix) { 59 TrieNode node = root; 60 char[] arr = prefix.toCharArray(); 61 for(char c : arr){ 62 if(node.children[c-‘a‘] == null){ 63 return false; 64 }else{ 65 node = node.children[c-‘a‘]; 66 } 67 } 68 return true; 69 70 } 71 }
208. Implement Trie (Prefix Tree)
原文:https://www.cnblogs.com/goPanama/p/9864465.html