Friday, October 9, 2020

Design Add and Search Words Data Structure

Problem: (Taken from leetcode) 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:

WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("apple");
wordDictionary.addWord("app");
wordDictionary.search("a.p") // returns true
wordDictionary.search("ap.") // returns true
wordDictionary.search("ap.l.") // returns true
wordDictionary.search(".p.l.") // returns true
wordDictionary.search(".p.l") // returns false


Approach: We can use Trie here. The main problem is to implement Search(). We can use PatterSearch of Trie which uses DFS internally.


Implementation in C#:

public class WordDictionary 

{

    public WordDictionary() 
    {
     this.trie = new Trie();   
    }
    
    public void AddWord(string word) 
    {
        trie.Insert(word);
    }
    
    public bool Search(string word) 
    {
        return trie.PatternSearch(word);
    }
    
    private Trie trie;



Complexity: O(n) if we consider that number of alphabets are constants

No comments:

Post a Comment