-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay 007-Design Add and Search Words Data Structure
48 lines (42 loc) · 1.58 KB
/
Day 007-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
// ( --- https://leetcode.com/problems/design-add-and-search-words-data-structure/ --- )
// 211. Design Add and Search Words Data Structure
class WordDictionary {
private WordDictionary[] children;
boolean isEndOfWord;
// Initialize your data structure here.
public WordDictionary() {
children = new WordDictionary[26];
isEndOfWord = false;
}
// Adds a word into the data structure.
public void addWord(String word) {
WordDictionary curr = this;
for(char c: word.toCharArray()){
if(curr.children[c - 'a'] == null)
curr.children[c - 'a'] = new WordDictionary();
curr = curr.children[c - 'a'];
}
curr.isEndOfWord = true;
}
// 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) {
WordDictionary curr = this;
for(int i = 0; i < word.length(); ++i){
char c = word.charAt(i);
if(c == '.'){
for(WordDictionary ch: curr.children)
if(ch != null && ch.search(word.substring(i+1))) return true;
return false;
}
if(curr.children[c - 'a'] == null) return false;
curr = curr.children[c - 'a'];
}
return curr != null && curr.isEndOfWord;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/