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.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
1 <= word.length <= 25word in addWord consists of lowercase English letters.word in search consist of '.' or lowercase English letters.2 dots in word for search queries.104 calls will be made to addWord and search.We can store each added word in a list and when a search operation is called, we'll iterate through all the stored words to check if there's any match to the search word. For search words having a wildcard character '.', we need to check each character except the wildcard positions. This approach is inefficient for large datasets due to the linear search which is coupled with string matching complexity.
A more efficient approach is to use a Trie (prefix tree) to store the added words. The trie allows us to efficiently search by traversing down the tree character by character, matching the structure of the search word. For each wildcard '.', we can traverse down all possible paths. This significantly reduces the time complexity for search operations compared to the brute force method.