题目链接:https://leetcode.com/problems/implement-trie-prefix-tree/ 题目:

insertsearch, and startsWithNote:

You may assume that all inputs are consist of lowercase letters a-z.

思路:

每个结点包括三个属性:结点代表的字符、指向儿子结点的指针、代表该结点是否是word。最后一个属性是因为word不一定是从根到叶结点的路径。比如insert("abc")、insert("ab"),search("ab")应该返回true。因为之前插入了ab,哪怕b不是叶结点,所以结点要有一个属性表示从root到该是否为word。

算法

 
    
 
1. import java.util.HashMap;  
2.   
3. class TrieNode {  
4. // Initialize your data structure here.  
5. "";  
6. new HashMap<String, TrieNode>();  
7. boolean isword = false;  
8. public TrieNode() {  
9.     }  
10. }  
11.   
12. public class Trie {  
13. private TrieNode root;  
14.   
15. public Trie() {  
16. new TrieNode();  
17.     }  
18.   
19. // Inserts a word into the trie.  
20. public void insert(String word) {  
21.         TrieNode p = root;  
22. for (int i = 0; i < word.length(); i++) {  
23. "";  
24. if (p.nexts.containsKey(key)) {  
25.                 p = p.nexts.get(key);  
26. else {  
27. new TrieNode();  
28.                 t.val = key;  
29.                 p.nexts.put(key, t);  
30.                 p = t;  
31.             }  
32. if(i==word.length()-1){  
33. true;  
34.             }  
35.         }  
36. ":"+p.isword);  
37.     }  
38.   
39. // Returns if the word is in the trie.  
40. public boolean search(String word) {  
41.         TrieNode p = root;  
42. for (int i = 0; i < word.length(); i++) {  
43. "";  
44. if (p.nexts.containsKey(key)) {  
45.                 p = p.nexts.get(key);  
46. else {  
47. return false;  
48.             }  
49.         }  
50. if (p.nexts.size() == 0)  
51. return true;  
52. else if(!p.isword)  
53. return false;  
54. else  
55. return true;  
56.     }  
57.   
58. // Returns if there is any word in the trie  
59. // that starts with the given prefix.  
60. public boolean startsWith(String prefix) {  
61.         TrieNode p = root;  
62. for (int i = 0; i < prefix.length(); i++) {  
63. "";  
64. if (p.nexts.containsKey(key)) {  
65.                 p = p.nexts.get(key);  
66. else {  
67. return false;  
68.             }  
69.         }  
70. return true;  
71.     }  
72. }