Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit88e9cd4

Browse files
authored
Update Implement Trie (Prefix Tree).java
1 parent1b560a3 commit88e9cd4

File tree

1 file changed

+28
-32
lines changed

1 file changed

+28
-32
lines changed
Lines changed: 28 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,56 @@
11
classTrie {
2-
3-
TrieNoderoot;
2+
3+
privateTrieNoderoot;
4+
45
publicTrie() {
5-
root =newTrieNode('-');
6+
this.root =newTrieNode();
67
}
78

89
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());
1714
}
15+
curr =curr.children.get(c);
1816
}
17+
curr.isWord =true;
1918
}
2019

2120
publicbooleansearch(Stringword) {
22-
TrieNodenode =searchHelper(word);
23-
returnnode !=null &&node.isWord;
21+
TrieNodesearchNode =searchHelper(word);
22+
returnsearchNode !=null &&searchNode.isWord;
2423
}
2524

2625
publicbooleanstartsWith(Stringprefix) {
2726
returnsearchHelper(prefix) !=null;
2827
}
2928

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)) {
3433
returnnull;
3534
}
36-
node =node.children[word.charAt(i) -'a'];
35+
curr =curr.children.get(c);
3736
}
38-
returnnode;
37+
returncurr;
3938
}
4039

41-
classTrieNode {
42-
TrieNode[]children;
40+
privateclassTrieNode {
41+
Map<Character,TrieNode>children;
4342
booleanisWord;
44-
charc;
4543

46-
publicTrieNode(charc) {
47-
this.c =c;
48-
children =newTrieNode[26];
49-
isWord =false;
44+
publicTrieNode() {
45+
this.children =newHashMap<>();
5046
}
5147
}
5248
}
5349

5450
/**
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+
*/

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp