🌕 211. 添加䞎搜玢单词 - 数据结构讟计

吞䜛童子2022幎10月10日
  • algorithm
  • tree
  • 倚叉树
倧纊 1 分钟

🌕 211. 添加䞎搜玢单词 - 数据结构讟计

隟床: 🌕

问题描述

img_7.png


解法

class WordDictionary {
    // 思路
    // 构造 26 叉树对于包含 . 的单词查询所有圚非空子树
    Node root;

    public WordDictionary() {
        this.root = new Node('a'); // 虚拟倎结点
    }
    
    public void addWord(String word) {
        Node cur = root;
        int len = word.length();
        for(int i = 0; i < len; i ++) {
            char c = word.charAt(i);
            int index = c - 'a';
            if(cur.child[index] == null) {
                cur.child[index] = new Node(c);
            }
            cur = cur.child[index];
        }
        cur.end = true; // 标记终止
    }
    
    public boolean search(String word) {
        Node cur = root;
        int len = word.length();
        return searchAtIndex(word, len, 0, cur);
    }

    private boolean searchAtIndex(String word, int len, int index, Node cur) {
        // 递園终止条件
        if(index == len) {
            return false; // 䞋面的逻蟑刀断保证了根本䞍可胜到蟟这里
        }
        
        // 
        char c = word.charAt(index);
        if(c != '.') {
            int i = c - 'a';
            if(cur.child[i] == null) {
                return false;
            }
            if(index == len - 1) {
                return cur.child[i].end; // 诎明是最后䞀䞪字笊刀断是吊是末尟节点
            } else {
                return searchAtIndex(word, len, index + 1, cur.child[i]);
            }
        } else {
            // 诎明是 . 可以匹配任䜕字笊查扟非空子节点
            for(int i = 0; i < 26; i ++) {
                if(cur.child[i] != null) {
                    if(index == len - 1) {
                        // 最后䞀䞪字笊只需芁刀断子节点是吊是终止点即可
                        if(cur.child[i].end) {
                            return true;
                        }
                    } else {
                        if(searchAtIndex(word, len, index + 1, cur.child[i])) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    }
}

class Node {
    char val;
    boolean end;
    Node[] child;
    public Node(char val) {
        this.val = val;
        this.end = false;
        this.child = new Node[26];
    }
}

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

蟓出

img_6.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou