Word Dictionary

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

  • Time: O(n)
  • Space: O(1)
public class WordDictionary {

    private TrieNode root;

    public WordDictionary() {
        root = new TrieNode();
    }

    // Adds a word into the data structure.
    public void addWord(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            if (node.childs[word.charAt(i) - 'a'] == null) {
                node.childs[word.charAt(i) - 'a'] = new TrieNode();
            }
            node = node.childs[word.charAt(i) - 'a'];
        }
        node.isWord = true;
    }

    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    public boolean search(String word) {
        return search(root, word, 0);
    }

    private boolean search(TrieNode node, String word, int i) {
        if (word.length() == i) {
            return node.isWord;
        }
        if (word.charAt(i) != '.') {
            return node.childs[word.charAt(i) - 'a'] != null && search(node.childs[word.charAt(i) - 'a'], word, i + 1);
        } else {
            for (int j = 0; j < node.childs.length; j++) {
                if (node.childs[j] != null) {
                    if (search(node.childs[j], word, i + 1)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

results matching ""

    No results matching ""