211. Design Add and Search Words Data Structure
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)
Addsword
to the data structure, it can be matched later.bool search(word)
Returnstrue
if there is any string in the data structure that matchesword
orfalse
otherwise.word
may contain dots'.'
where dots can be matched with any letter.
Constraints
1 <= word.length <= 500
word
inaddWord
consists lower-case English letters.word
insearch
consist of'.'
or lower-case English letters.At most
50000
calls will be made toaddWord
andsearch
.
Approach
Links
GeeksforGeeks
YouTube
Examples
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
Solutions
/**
* Time complexity : O(M), where M is the key length. At each
* step, we either examine or create a node in the trie.
* That takes only M operations.
* Space complexity : O(M). In the worst-case newly inserted
* key doesn't share a prefix with the keys already
* inserted in the trie. We have to add M new nodes,
* which takes O(M) space.
*/
class WordDictionary {
private Map<Integer, Set<String>> dict;
/** Initialize your data structure here. */
public WordDictionary() {
dict = new HashMap();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
int m = word.length();
if(!dict.containsKey(m)) {
dict.put(m, new HashSet());
}
dict.get(m).add(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) {
int m = word.length();
if(dict.containsKey(m)) {
for(String w: dict.get(m)) {
int i = 0;
while(i < m &&
(w.charAt(i) == word.charAt(i) ||
word.charAt(i) == '.')) {
i++;
}
if(i == m) return true;
}
}
return false;
}
}
/**
* Your WordDictionary object will be instantiated and
* called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
Follow up
Last updated
Was this helpful?