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)Addswordto the data structure, it can be matched later.bool search(word)Returnstrueif there is any string in the data structure that matcheswordorfalseotherwise.wordmay contain dots'.'where dots can be matched with any letter.
Example:
Input
[“WordDictionary”,“addWord”,“addWord”,“addWord”,“search”,“search”,“search”,“search”]
[[],[“bad”],[“dad”],[“mad”],[“pad”],[“bad”],[“.ad”],[“b..”]]
Output
[null,null,null,null,false,true,true,true]
Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
Constraints:
1 <= word.length <= 25wordinaddWordconsists of lowercase English letters.wordinsearchconsist of'.'or lowercase English letters.- There will be at most
2dots inwordforsearchqueries. - At most
104calls will be made toaddWordandsearch.
Approach - DFS
- Similar to original question but there is difference as we encounter . then we have to go through all the values otherwise it is usual day business
class Trie {
Map<Character,Trie> child = new HashMap<>();
boolean end = false;
}
class WordDictionary {
Trie root;
public WordDictionary() {
root = new Trie();
}
public void addWord(String word) {
Trie current = root;
for (char c: word.toCharArray()) {
current.child.putIfAbsent(c,new Trie());
current = current.child.get(c);
}
current.end = true;
}
public boolean search(String word) {
return dfs(word.toCharArray(),0,root);
}
public boolean dfs(char[] word, int index, Trie node) {
if (index == word.length)
return node.end;
char c = word[index];
if (c == '.') {
for (Trie next: node.child.values()) {
if (dfs(word, index + 1, next))
return true;
}
return false;
} else {
Trie next = node.child.get(c);
if (next == null)
return false;
return dfs(word, index + 1, next);
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/