Skip to content

Design Add and Search Words Data Structure

Roberto Fronteddu edited this page Aug 9, 2024 · 1 revision

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.
class WordDictionary {
    class TrieNode {
        Map<Character, TrieNode> children = new HashMap<>();
        boolean isWord;
    }
    TrieNode root;
    
    public WordDictionary() {
        root = new TrieNode();
    }
    
    public void addWord(String word) {
        var cur = root;
        for (Character c : word.toCharArray()) {
            if(!cur.children.containsKey(c)) {
                cur.children.put (c, new TrieNode());
            }
            cur = cur.children.get(c);
        }
        cur.isWord = true;
    }
    
    public boolean search(String word) {
        var cur = root;
        var wordArray = word.toCharArray();
        for (int i = 0; i < wordArray.length; i++) {
            if (!cur.children.containsKey(wordArray[i])) {
                if (wordArray[i] == '.') {
                    for (var child : cur.children.entrySet()) {
                        if (searchChild(i+1, wordArray, child.getValue())) {
                            return true;
                        }
                    }
                }
                return false;
            } else {
                cur = cur.children.get(wordArray[i]);
            }
        }
        return cur.isWord;
    }
    boolean searchChild (int i, char[] wordArray, TrieNode cur) {
        for (; i < wordArray.length; i++) {
            if (!cur.children.containsKey (wordArray[i])) {
                if (wordArray[i] == '.') {
                    for (var child : cur.children.entrySet()) {
                        if (searchChild (i+1, wordArray, child.getValue())) {
                            return true;
                        }
                    }
                    return false;
                }
                return false;
            }
            cur = cur.children.get(wordArray[i]);
        }
        
        if (cur == null) {
            return false;
        }
        return cur.isWord;
    }
}

Clone this wiki locally