-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo211DesignAddAndSearchWordsDataStructure.java
82 lines (67 loc) · 2.01 KB
/
No211DesignAddAndSearchWordsDataStructure.java
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
package com.wzx.leetcode;
import java.util.Deque;
import java.util.LinkedList;
/**
* @author wzx
* @see <a href="https://leetcode.com/problems/design-add-and-search-words-data-structure/description/">https://leetcode.com/problems/design-add-and-search-words-data-structure/description/</a>
*/
public class No211DesignAddAndSearchWordsDataStructure {
private static class TieTreeNode {
public boolean leaf = false;
private final TieTreeNode[] children = new TieTreeNode[26];
public boolean hasChild(char ch) {
return children[ch - 'a'] != null;
}
public TieTreeNode getChild(char ch) {
return children[ch - 'a'];
}
public TieTreeNode setChild(char ch) {
if (!hasChild(ch)) children[ch - 'a'] = new TieTreeNode();
return children[ch - 'a'];
}
}
/**
* 字典树
*/
public static class WordDictionary {
private final TieTreeNode root = new TieTreeNode();
public WordDictionary() {
}
/**
* 最后一位设置为leaf,一个word的结束
*/
public void addWord(String word) {
TieTreeNode node = root;
for (char ch : word.toCharArray()) {
node = node.setChild(ch);
}
node.leaf = true;
}
/**
* bfs
*/
public boolean search(String word) {
Deque<TieTreeNode> queue = new LinkedList<>();
queue.add(root);
for (char ch : word.toCharArray()) {
if (queue.isEmpty()) return false;
int size = queue.size();
for (int i = 0; i < size; i++) {
TieTreeNode node = queue.pollFirst();
// 遇到.则添加所有子节点
if (ch == '.') {
for (char j = 'a'; j < 'z'; j++) {
if (node.hasChild(j)) {
queue.addLast(node.getChild(j));
}
}
} else if (node.hasChild(ch)) {
queue.addLast(node.getChild(ch));
}
}
}
// 匹配的最后一位是否是leaf
return queue.stream().anyMatch(node -> node.leaf);
}
}
}