Advanced
Open
Pro
Insert and Search Words with Wildcards
Design a data structure that supports adding new words and then
searching for a word, where the search word may contain the .
wildcard character, which can match any single letter.
Implement:
addWord(word): addswordto the dictionary.search(query): returnstrueif there is a word in the dictionary that matchesquery.querymay contain the lettersa-zand the character., where each.may match any one letter. The matched word must be exactly the same length asquery.
Example 1
dict = WordDictionary()
dict.addWord("bad")
dict.addWord("dad")
dict.addWord("mad")
dict.search("pad") # -> false ("pad" was never added)
dict.search("bad") # -> true
dict.search(".ad") # -> true (matches "bad", "dad", or "mad")
dict.search("b..") # -> true (matches "bad")
dict.search("b.d") # -> true (matches "bad")
dict.search("...") # -> true (any 3-letter word matches)
dict.search("....") # -> false (no 4-letter word was added)
Constraints
1 <= word.length, query.length <= 25wordconsists of lowercase English letters.queryconsists of lowercase English letters and/or..- At most
10^4calls total toaddWordandsearchcombined. - At most 2 dots appear in any single
searchcall in the worst realistic test cases, but your solution should handle more.
Share this question