208-Trie树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Trie {
static class Node{
boolean end =false;
Node []son =new Node[26];
}
Node root =new Node();
public Trie() {

}
public void insert(String word) {
Node curr =root;
for(char arr:word.toCharArray()){
arr -='a';
if(curr.son[arr] == null){
curr.son[arr] =new Node();
}
curr = curr.son[arr];
}
curr.end =true;
}

public boolean search(String word) {
return getTrie(word)==2;
}

public boolean startsWith(String prefix) {
return getTrie(prefix)!=0;
}
int getTrie(String word){
Node arr =root;
for(char now:word.toCharArray()){
now-='a';
if(arr.son[now]==null){
return 0;
}
arr = arr.son[now];
}
return arr.end == true?2:1;
}
}

/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/

208-Trie树
http://example.com/2025/11/17/力扣208Trie树/
作者
無鎏雲
发布于
2025年11月17日
许可协议