标签:
1 class TrieNode { 2 // Initialize your data structure here. 3 TrieNode[] children = new TrieNode[26]; 4 boolean isWord; 5 public TrieNode() { 6 } 7 } 8 9 public class Trie { 10 private TrieNode root; 11 12 public Trie() { 13 root = new TrieNode(); 14 } 15 16 // Inserts a word into the trie. 17 public void insert(String word) { 18 TrieNode current = root; 19 for (int i = 0; i < word.length(); i++) { 20 if (current.children[word.charAt(i) - ‘a‘] == null) { 21 current.children[word.charAt(i) - ‘a‘] = new TrieNode(); 22 } 23 current = current.children[word.charAt(i) - ‘a‘]; 24 } 25 current.isWord = true; 26 } 27 28 // Returns if the word is in the trie. 29 public boolean search(String word) { 30 TrieNode current = root; 31 for (int i = 0; i < word.length(); i++) { 32 if (current.children[word.charAt(i) - ‘a‘] == null) { 33 return false; 34 } 35 current = current.children[word.charAt(i) - ‘a‘]; 36 } 37 return current.isWord; 38 } 39 40 // Returns if there is any word in the trie 41 // that starts with the given prefix. 42 public boolean startsWith(String prefix) { 43 TrieNode current = root; 44 for (int i = 0; i < prefix.length(); i++) { 45 if (current.children[prefix.charAt(i) - ‘a‘] == null) { 46 return false; 47 } 48 current = current.children[prefix.charAt(i) - ‘a‘]; 49 } 50 return true; 51 } 52 } 53 54 // Your Trie object will be instantiated and called as such: 55 // Trie trie = new Trie(); 56 // trie.insert("somestring"); 57 // trie.search("key");
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/5628756.html