
Problem
Solution
Submissions
Design Add and Search Words Data Structure
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C# program to implement a WordDictionary
class that supports adding new words and finding if a word matches a given pattern. The pattern may contain the dot character '.' which can match any single letter.
Example 1
- 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:
- Step 1: Create a new WordDictionary instance.
- WordDictionary wordDictionary = new WordDictionary();
- Step 2: Add words to the dictionary.
- wordDictionary.addWord("bad");
- wordDictionary.addWord("dad");
- wordDictionary.addWord("mad");
- Step 3: Search for words in the dictionary.
- wordDictionary.search("pad") returns false (not in dictionary).
- wordDictionary.search("bad") returns true (exact match).
- wordDictionary.search(".ad") returns true (matches "bad", "dad", or "mad").
- wordDictionary.search("b..") returns true (matches "bad").
- Step 4: Return the results of all operations.
- Step 1: Create a new WordDictionary instance.
Example 2
- Input:
["WordDictionary","addWord","addWord","search","search","search","search"]
[[],["at"],["bat"],["bat"],["at"],[".at"],["an"]] - Output: [null,null,null,true,true,true,false]
- Explanation:
- Step 1: Create a new WordDictionary instance.
- WordDictionary wordDictionary = new WordDictionary();
- Step 2: Add words to the dictionary.
- wordDictionary.addWord("at");
- wordDictionary.addWord("bat");
- Step 3: Search for words in the dictionary.
- wordDictionary.search("bat") returns true (exact match).
- wordDictionary.search("at") returns true (exact match).
- wordDictionary.search(".at") returns true (matches "bat" or "at").
- wordDictionary.search("an") returns false (not in dictionary).
- Step 4: Return the results of all operations.
- Step 1: Create a new WordDictionary instance.
Constraints
- 1 ≤ word.length ≤ 25
- Words consist of lowercase English letters only
- The dot character '.' may be used to represent any letter
- At most 10^4 calls will be made to addWord and search
- Time Complexity: O(M) for adding words and O(M * 26^N) for searching words with wildcards, where M is the word length
- Space Complexity: O(M) where M is the total number of characters in all words
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a Trie (prefix tree) data structure to store the words
- Implement a DFS algorithm to handle wildcard searches
- For wildcard characters, explore all possible child nodes
- Maintain a flag at each node to indicate if it represents the end of a word