标签:
原题链接在这里:https://leetcode.com/problems/implement-trie-prefix-tree/
Trie 是一种数据结构,用来做字典查找,是一种用于快速检索的多叉数结构。例如,英文字母的字典树是26叉数,数字的字典树是10叉树。
Trie树的基本性质有三点,归纳为:
Note: search() 和 startsWith() 有所不同,search时还需要注意跳出loop时是否已经打了Trie树的叶子节点。
AC Java:
1 class TrieNode { 2 //Mark if this node is the end of the word 3 boolean isLeaf; 4 HashMap<Character,TrieNode> nexts; 5 public TrieNode() { 6 nexts = new HashMap<Character,TrieNode>(); 7 } 8 } 9 10 public class Trie { 11 private TrieNode root; 12 13 public Trie() { 14 root = new TrieNode(); 15 } 16 17 // Inserts a word into the trie. 18 public void insert(String word) { 19 TrieNode p = root; 20 char [] s = word.toCharArray(); 21 int len = s.length; 22 int i = 0; 23 //traverse the existing character 24 while(i<len){ 25 if(p.nexts.containsKey(s[i])){ 26 p = p.nexts.get(s[i]); 27 i++; 28 }else{ 29 break; 30 } 31 } 32 //append new nodes 33 while(i<len){ 34 TrieNode newNode = new TrieNode(); 35 p.nexts.put(s[i],newNode); 36 p = newNode; 37 i++; 38 } 39 //Set the end of the word 40 p.isLeaf = true; 41 } 42 43 // Returns if the word is in the trie. 44 public boolean search(String word) { 45 TrieNode p = root; 46 char [] s = word.toCharArray(); 47 int len = s.length; 48 int i = 0; 49 while(i<len){ 50 TrieNode nextNode = p.nexts.get(s[i]); 51 if(nextNode == null){ 52 return false; 53 } 54 p = nextNode; 55 i++; 56 } 57 //return if this is a leaf node 58 return p.isLeaf; 59 } 60 61 // Returns if there is any word in the trie 62 // that starts with the given prefix. 63 public boolean startsWith(String prefix) { 64 TrieNode p = root; 65 char [] s = prefix.toCharArray(); 66 int len = s.length; 67 int i = 0; 68 while(i<len){ 69 TrieNode nextNode = p.nexts.get(s[i]); 70 if(nextNode == null){ 71 return false; 72 } 73 p = nextNode; 74 i++; 75 } 76 return true; 77 } 78 } 79 80 // Your Trie object will be instantiated and called as such: 81 // Trie trie = new Trie(); 82 // trie.insert("somestring"); 83 // trie.search("key");
参考了这篇帖子:http://blog.csdn.net/wzy_1988/article/details/45744067#trie树基本实现
LeetCode Implement Trie (Prefix Tree)
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4888830.html