LeetCode 211: Add and Search Word

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 211: Add and Search Word相关的知识,希望对你有一定的参考价值。

class WordDictionary {
    class TrieNode {
        public TrieNode[] children = new TrieNode[26];
        public boolean isEnd;
    }
    
    private 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 runner = root;
        for (char c : word.toCharArray()) {
            if (runner.children[(int)(c - ‘a‘)] == null) {
                runner.children[(int)(c - ‘a‘)] = new TrieNode();
            }
            runner = runner.children[(int)(c - ‘a‘)];
        }
        runner.isEnd = 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(word.toCharArray(), 0, root);
    }
    
    private boolean search(char[] word, int index, TrieNode current) {
        if (index == word.length) {
            return current.isEnd;
        }
        
        if (word[index] != ‘.‘) {
            return current.children[(int)(word[index] - ‘a‘)] != null && search(word, index + 1, current.children[(int)(word[index] - ‘a‘)]);
        } else {
            boolean found = false;
            for (int i = 0; i < 26; i++) {
                if (current.children[i] != null && search(word, index + 1, current.children[i])) {
                    return true;
                }
            }
        }
        return false;
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */

 

1. When dot happened, each path should be scanned.

2. Each node will not contain any current char info.

以上是关于LeetCode 211: Add and Search Word的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-211 Add and Search Word - Data structure design

leetcode 211. Add and Search Word - Data structure design

Leetcode 211: Add and Search Word - Data structure design

[LeetCode] 211. Add and Search Word - Data structure design Java

[leetcode trie]211. Add and Search Word - Data structure design

LeetCode 211. Add and Search Word - Data structure design(字典树)