211. Add and Search Word - Data structure design
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 lettersa-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
FB follow up: process "*"
Thoughts:
- Trie Tree excercise
class WordDictionary {
private TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
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;
}
/** 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 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);
*/
Python
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
node = self.root
for s in word:
if s not in node.child:
node.child[s] = TrieNode()
node = node.child[s]
node.val = word
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
def match(word, depth, node):
if depth == len(word): return not (node.val=='')
if word[depth] != '.':
return word[depth] in node.child and match(word, depth + 1, node.child[word[depth]])
else:
for c in node.child:
if match(word, depth+1, node.child[c]):
return True
return False
return match(word, 0, self.root)
class TrieNode(object):
def __init__(self):
self.child = {}
self.val = ""
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
Python: length based dictionary: psudu- O(1) - O(n)-> for char level: O(len(char in table entry))
class WordDictionary(object):
def __init__(self):
self.word_dict = collections.defaultdict(list)
def addWord(self, word):
if word:
self.word_dict[len(word)].append(word)
def search(self, word):
if not word:
return False
if '.' not in word:
return word in self.word_dict[len(word)]
for v in self.word_dict[len(word)]:
# match xx.xx.x with yyyyyyy
for i, ch in enumerate(word):
if ch != v[i] and ch != '.':
break
else: # if no break in previous for loop;
return True
return False
Python: best Trie Implementation: T: O(len(total words)); S: O(len(total words))
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
node = self.root
for s in word:
if s not in node.child:
node.child[s] = TrieNode()
node = node.child[s]
node.val = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
def match(word, node):
for i, c in enumerate(word):
if c == '.':
for s in node.child:
if match(word[i + 1:], node.child[s]):
return True
return False #!
elif c not in node.child:
return False
node = node.child[c]
return node.val
return match(word, self.root)
class TrieNode(object):
def __init__(self):
self.child = {}
self.val = False
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)