-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathAddAndSearchWord.java
More file actions
72 lines (66 loc) · 1.99 KB
/
AddAndSearchWord.java
File metadata and controls
72 lines (66 loc) · 1.99 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
public class WordDictionary {
private Trie trie;
public WordDictionary() {
trie = new Trie();
}
// Adds a word into the data structure.
public void addWord(String word) {
trie.add(word);
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
public boolean search(String word) {
return trie.search(word);
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
class TrieNode {
// Initialize your data structure here.
public TrieNode[] list;
public boolean leaf;
public TrieNode() {
list = new TrieNode[26];
leaf = false;
}
}
class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void add(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (current.list[index] == null) {
current.list[index] = new TrieNode();
}
current = current.list[index];
}
current.leaf = true;
}
public boolean search(String word) {
return dfs(word, 0, root);
}
public boolean dfs(String word, int index, TrieNode node) {
if (node == null) return false;
if (index == word.length()) return node.leaf;
boolean res = false;
if (word.charAt(index) == '.') {
for (int i = 0; i < 26; i++) {
res = res || dfs(word, index + 1, node.list[i]);
}
} else {
int next = word.charAt(index) - 'a';
if (node.list[next] == null)
return false;
else
res = dfs(word, index + 1, node.list[next]);
}
return res;
}
}