-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode208.java
More file actions
83 lines (73 loc) · 2.04 KB
/
LeetCode208.java
File metadata and controls
83 lines (73 loc) · 2.04 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.HashMap;
public class LeetCode208 {
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
System.out.println(trie.search("apple")); // 返回 True
System.out.println(trie.search("app")); // 返回 False
System.out.println(trie.startsWith("app")); // 返回 True
trie.insert("app");
System.out.println(trie.search("app")); // 返回 True
}
}
/**
* 构造一个字典树,可以将children的类型改为Node[]
*/
class Trie {
class Node {
public HashMap<Character, Node> children = new HashMap<>();
public boolean isWord = false;
public void insert(char c) {
children.put(c, new Node());
}
public boolean contains(char c) {
return children.containsKey(c);
}
public Node get(char c) {
return children.get(c);
}
public int childCount() {
return children.size();
}
}
private Node root = new Node();
public void insert(String word) {
Node curr = root;
int ind = 0;
while (ind < word.length()) {
char c = word.charAt(ind);
if (!curr.contains(c)) {
curr.insert(c);
}
curr = curr.get(c);
ind++;
}
curr.isWord = true;
}
public boolean search(String word) {
Node curr = root;
int ind = 0;
while (ind < word.length()) {
char c = word.charAt(ind);
if (!curr.contains(c)) {
return false;
}
curr = curr.get(c);
ind++;
}
return curr.isWord;
}
public boolean startsWith(String prefix) {
Node curr = root;
int ind = 0;
while (ind < prefix.length()) {
char c = prefix.charAt(ind);
if (!curr.contains(c)) {
return false;
}
curr = curr.get(c);
ind++;
}
return true;
}
}