Description
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
- WordDictionary() Initializes the object.
- void addWord(word) Adds word to the data structure, it can be matched later.
- bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots ‘.’ where dots can be matched with any letter.
Example
1 | Input |
Constraints:
- 1 <= word.length <= 500
- word in addWord consists lower-case English letters.
- word in search consist of ‘.’ or lower-case English letters.
- At most 50000 calls will be made to addWord and search.
Solution
Solution 1: HashMap, O(MN^2)
1 | // O(N^2 * M) |
Solution 2: Trie Tree, O(MN) for defined words without dots, O(NM^26) for undefined words1
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
51class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isWord = false;
public TrieNode(){
}
}
class WordDictionary {
private TrieNode node;
public WordDictionary() {
node = new TrieNode();
}
public void addWord(String word) {
TrieNode cur = node;
for (char ch: word.toCharArray()){
if (!cur.children.containsKey(ch)){
cur.children.put(ch, new TrieNode());
}
cur = cur.children.get(ch);
}
cur.isWord = true;
}
private boolean searchTrieTree(TrieNode node, String word){
for (int i = 0; i < word.length(); i++){
char ch = word.charAt(i);
if (!node.children.containsKey(ch)){
if (ch == '.'){
for (char c: node.children.keySet()) {
TrieNode child = node.children.get(c);
if (searchTrieTree(child, word.substring(i + 1))){
return true;
}
}
}
return false;
}
else{
node = node.children.get(ch);
}
}
return node.isWord;
}
public boolean search(String word) {
return searchTrieTree(node,word);
}
}