|
1 | 1 | classTrie {
|
2 |
| - |
3 |
| -TrieNoderoot; |
| 2 | + |
| 3 | +privateTrieNoderoot; |
| 4 | + |
4 | 5 | publicTrie() {
|
5 |
| -root =newTrieNode('-'); |
| 6 | +this.root =newTrieNode(); |
6 | 7 | }
|
7 | 8 |
|
8 | 9 | publicvoidinsert(Stringword) {
|
9 |
| -TrieNodenode =root; |
10 |
| -for (inti =0;i <word.length();i++) { |
11 |
| -if (node.children[word.charAt(i) -'a'] ==null) { |
12 |
| -node.children[word.charAt(i) -'a'] =newTrieNode(word.charAt(i)); |
13 |
| - } |
14 |
| -node =node.children[word.charAt(i) -'a']; |
15 |
| -if (i ==word.length() -1) { |
16 |
| -node.isWord =true; |
| 10 | +TrieNodecurr =root; |
| 11 | +for (charc :word.toCharArray()) { |
| 12 | +if (!curr.children.containsKey(c)) { |
| 13 | +curr.children.put(c,newTrieNode()); |
17 | 14 | }
|
| 15 | +curr =curr.children.get(c); |
18 | 16 | }
|
| 17 | +curr.isWord =true; |
19 | 18 | }
|
20 | 19 |
|
21 | 20 | publicbooleansearch(Stringword) {
|
22 |
| -TrieNodenode =searchHelper(word); |
23 |
| -returnnode !=null &&node.isWord; |
| 21 | +TrieNodesearchNode =searchHelper(word); |
| 22 | +returnsearchNode !=null &&searchNode.isWord; |
24 | 23 | }
|
25 | 24 |
|
26 | 25 | publicbooleanstartsWith(Stringprefix) {
|
27 | 26 | returnsearchHelper(prefix) !=null;
|
28 | 27 | }
|
29 | 28 |
|
30 |
| -privateTrieNodesearchHelper(Stringword) { |
31 |
| -TrieNodenode =root; |
32 |
| -for (inti =0;i <word.length();i++) { |
33 |
| -if (node.children[word.charAt(i) -'a'] ==null) { |
| 29 | +privateTrieNodesearchHelper(Strings) { |
| 30 | +TrieNodecurr =root; |
| 31 | +for (charc :s.toCharArray()) { |
| 32 | +if (!curr.children.containsKey(c)) { |
34 | 33 | returnnull;
|
35 | 34 | }
|
36 |
| -node =node.children[word.charAt(i) -'a']; |
| 35 | +curr =curr.children.get(c); |
37 | 36 | }
|
38 |
| -returnnode; |
| 37 | +returncurr; |
39 | 38 | }
|
40 | 39 |
|
41 |
| -classTrieNode { |
42 |
| -TrieNode[]children; |
| 40 | +privateclassTrieNode { |
| 41 | +Map<Character,TrieNode>children; |
43 | 42 | booleanisWord;
|
44 |
| -charc; |
45 | 43 |
|
46 |
| -publicTrieNode(charc) { |
47 |
| -this.c =c; |
48 |
| -children =newTrieNode[26]; |
49 |
| -isWord =false; |
| 44 | +publicTrieNode() { |
| 45 | +this.children =newHashMap<>(); |
50 | 46 | }
|
51 | 47 | }
|
52 | 48 | }
|
53 | 49 |
|
54 | 50 | /**
|
55 |
| -* Your Trie object will be instantiated and called as such: |
56 |
| -* Trie obj = new Trie(); |
57 |
| -* obj.insert(word); |
58 |
| -* boolean param_2 = obj.search(word); |
59 |
| -* boolean param_3 = obj.startsWith(prefix); |
60 |
| -*/ |
| 51 | +* Your Trie object will be instantiated and called as such: |
| 52 | +* Trie obj = new Trie(); |
| 53 | +* obj.insert(word); |
| 54 | +* boolean param_2 = obj.search(word); |
| 55 | +* boolean param_3 = obj.startsWith(prefix); |
| 56 | +*/ |