- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddAndSearchWord.java
More file actions
Latest commit
82 lines (74 loc) · 2.54 KB
/
Copy pathAddAndSearchWord.java
File metadata and controls
82 lines (74 loc) · 2.54 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
publicclassAddAndSearchWord {
/**
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
*/
classNode {
booleanisWord;
charval;
Node[] children;
publicNode(charval, booleanisWord) {
this.val = val;
children = newNode[26];
this.isWord = isWord;
}
}
privateNodehead; // Store a dummy node that have 26 children
/** Initialize your data structure here. */
publicAddAndSearchWord() {
head = newNode('A', false);
}
/** Adds a word into the data structure. */
publicvoidaddWord(Stringword) {
if (word == null) return;
char[] cArr = word.toCharArray();
Nodecur = head;
for (charc : cArr) {
if (cur.children[c - 'a'] == null) {
cur.children[c - 'a'] = newNode(c, false);
}
cur = cur.children[c - 'a'];
}
cur.isWord = true;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
publicbooleansearch(Stringword) {
if (word == null || word.length() == 0) returntrue;
returnsearch(word, this.head);
}
/**
Return true if there is word under the given head
*/
publicbooleansearch(Stringword, Nodehead) {
if (word == null || head == null) returnfalse;
if (word.length() == 0 && head.isWord) returntrue;
if (word.length() == 0) returnfalse;
charc = word.charAt(0);
if (c == '.') {
for (Nodechild : head.children) {
if (search(word.substring(1, word.length()), child))
returntrue;
}
returnfalse;
}
returnsearch(word.substring(1, word.length()), head.children[c - 'a']);
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
}