Leetcode_676_实现一个魔法字典_trie树

构造trie树即可
比较坑的是next数组的判空

class MagicDictionary {

    Node    root;
    boolean isSuccess;

    public MagicDictionary() {
        root = new Node();
    }

    public void buildDict(String[] dictionary) {
        for (String s : dictionary) {
            build(root, s, 0);
        }
    }

    public boolean search(String searchWord) {
        isSuccess = false;
        dfs(root, searchWord, 0, false);
        return isSuccess;
    }

    void build(Node node, String s, int index) {
        if (node.next == null) {
            node.next = new Node[26];
        }
        char c = s.charAt(index);
        int key = c - 'a';
        if (node.next[key] == null) {
            node.next[key] = new Node();
        }
        Node next = node.next[key];
        next.c = c;
        if (index == s.length() - 1) {
            next.end = true;
            return;
        }
        build(next, s, index + 1);
    }
    
    void dfs(Node node, String s, int index, boolean isChange) {
        if (isSuccess) {
            return;
        }
        if (index == s.length()) {
            if (node.end && isChange) {
                isSuccess = true;
            }
            return;
        }
        char c = s.charAt(index);
        int key = c - 'a';
        Node[] next = node.next;
        if(next == null) {
            return;
        }
        // 没有使用过万能权
        if (!isChange) {
            for (int i = 0; i < 26; i++) {
                if (next[i] != null && i != key) {
                    dfs(next[i], s, index + 1, true);
                }
            }
        }
        if (next[key] != null) {
            dfs(next[key], s, index + 1, isChange);
        }
    }
}

class Node {
    char    c;
    Node[]  next;
    boolean end;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值