-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path211. Design Add and Search Words Data Structure
57 lines (54 loc) · 1.43 KB
/
211. Design Add and Search Words Data Structure
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
class WordDictionary
{
private TrieNode root;
public WordDictionary()
{
root = new TrieNode();
}
public void addWord(String word)
{
TrieNode node = root;
for (char c: word.toCharArray())
{
if(node.children[c - 'a'] == null)
{
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.val = word;
}
public boolean search(String word)
{
return match(word, 0, root);
}
private boolean match(String word, int depth, TrieNode node)
{
if(depth == word.length())
return !node.val.equals("");
if(word.charAt(depth) != '.')
{
return (node.children[word.charAt(depth) - 'a'] != null && match(word, depth + 1, node.children[word.charAt(depth) - 'a'] ));
}
else
{
for (int i = 0; i < node.children.length; i++)
{
if(node.children[i] != null && match(word, depth + 1, node.children[i]))
return true;
}
}
return false;
}
}
class TrieNode
{
public TrieNode [] children = new TrieNode[26];
public String val = "";
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/