lc-211


请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。

实现词典类 WordDictionary

  • WordDictionary() 初始化词典对象
  • void addWord(word)word 添加到数据结构中,之后可以对它进行匹配
  • bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 falseword 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。

示例:

输入:
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
输出:
[null,null,null,null,false,true,true,true]

解释:
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // 返回 False
wordDictionary.search("bad"); // 返回 True
wordDictionary.search(".ad"); // 返回 True
wordDictionary.search("b.."); // 返回 True

提示:

  • 1 <= word.length <= 25
  • addWord 中的 word 由小写英文字母组成
  • search 中的 word 由 ‘.’ 或小写英文字母组成
  • 最多调用 104addWordsearch

//leetcode submit region begin(Prohibit modification and deletion)
class WordDictionary {
    private Trie root;

    public WordDictionary() {
        this.root = new Trie();
    }

    public void addWord(String word) {
        if (word == null || word.length() == 0) {
            return;
        }
        Trie cur = this.root;
        for (char ch : word.toCharArray()) {
            if (cur.children[ch - 'a'] == null) {
                cur.children[ch - 'a'] = new Trie();
            }
            cur = cur.children[ch - 'a'];
        }
        cur.hasWord = true;
    }

    public boolean search(String word) {
        return matched(root, word.toCharArray(), 0);
    }

    private boolean matched(Trie trie, char[] charArr, int index) {
        if (trie == null) {
            return false;
        }

        if (index == charArr.length) {
            return trie.hasWord;
        }

        char ch = charArr[index];
        if (ch == '.') {
            for (int i = 0; i < 26; i++) {
                boolean match = matched(trie.children[i], charArr, index + 1);
                if (match) {
                    return true;
                }
            }
            return false;
        } else {
            return matched(trie.children[ch - 'a'], charArr, index + 1);
        }
    }

    private class Trie {
        Trie[] children;
        boolean hasWord;

        public Trie() {
            this.children = new Trie[26];
            this.hasWord = false;
        }
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !