Thinking process

Use a trie, but how to handle . ?

  • recursively

Mistakes

don't forget to check whether the child exists

class TrieNode {
    public TrieNode[] children;
    public boolean isWord;
    public TrieNode() {
        children = new TrieNode[26];
        isWord = false;
    }
}

public class WordDictionary {
    public TrieNode root;
    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new TrieNode();
    }

    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode node = root;

        for (char c : word.toCharArray()) {
            if (node.children[c - 'a'] == null) {
                TrieNode child = new TrieNode();
                node.children[c - 'a'] = child;
                node = child;
            } else {
                node = node.children[c - '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 dfsHelper(word.toCharArray(), 0, root);
    }

    private boolean dfsHelper(char[] chars, int index, TrieNode node) {
        if (index >= chars.length) {
            return node.isWord;
        }

        if (chars[index] == '.') {
            for (int i = 0; i < node.children.length; ++i) {
                if (node.children[i] != null && dfsHelper(chars, index + 1, node.children[i])) {
                    return true;
                }
            }
        } else {
            if (node.children[chars[index] - 'a'] != null) {
                return dfsHelper(chars, index + 1, node.children[chars[index] - 'a']);
            }
        }

        return false;
    }
}

results matching ""

    No results matching ""