[Leetcode] 0211. Design Add and Search Words Data Structure

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link

内容目录

Medium


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.

 

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 <= 25
  • word in addWord consists of lowercase English letters.
  • word in search consist of '.' or lowercase English letters.
  • There will be at most 2 dots in word for search queries.
  • At most 10 4 calls will be made to addWord and search.

Python

				
					# time complexity: O(M) # space complexity: O(M) class TrieNode: def __init__(self): self.children = {} self.isEnd = False class WordDictionary: def __init__(self): self.root = TrieNode() self.maxLen = 0 def addWord(self, word: str) -> None: node = self.root l = 0 for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] l += 1 self.maxLen = max(self.maxLen, l) node.isEnd = True def search(self, word: str) -> bool: if len(word) > self.maxLen: return False def helper(idx, node): for i in range(idx, len(word)): if word[i] == ".": for child in node.children.values(): if helper(i + 1, child): return True return False else: if word[i] not in node.children: return False node = node.children[word[i]] return node.isEnd return helper(0, self.root) wordDictionary = WordDictionary() wordDictionary.addWord("bad") wordDictionary.addWord("dad") wordDictionary.addWord("mad") print(wordDictionary.search("pad")) print(wordDictionary.search("bad")) print(wordDictionary.search(".ad")) print(wordDictionary.search("b.."))
				
			
zh_CN简体中文