Leetcode211. 添加与搜索单词 - 数据结构设计 字典树

记录日常学习与做题

字典树模板题

由于本题存在通配符 故需要对查找再进行递归

思路:额外申请一个空间用于存放通配符’.’
在查找中,若既不匹配字符又不匹配通配符 返回false,当遇到通配符时,对child所有节点递归,若遇到其中一个满足条件 返回true

class WordDictionary {

    class Node {
        Node[] child;
        boolean isleaf;

        public Node() {
            child = new Node[27];//最后一个用来往'.'
            isleaf = false;
        }
    }

    private Node node;
    /**
     * Initialize your data structure here.
     */
    public WordDictionary() {
        node = new Node();
    }
	//字典树插入模板
    private void insert(Node node, String word) {
        char[] chars = word.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            int index = chars[i] - 'a';
            if (chars[i] == '.') { //如果遇到了通配符'.' 将其置为26
                index = 26;
            }
            if (node.child[index] == null) {
                node.child[index] = new Node();
            }
            if (i == chars.length - 1) {
                node.child[index].isleaf = true;
            }
            node = node.child[index];
        }
    }

    public void addWord(String word) {
        insert(this.node, word);
    }

    public boolean search(String word) {
        return find(this.node, word);
    }

    private boolean find(Node root, String word) {
        char[] chars = word.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            int index = chars[i] - 'a';
            //对遇到通配符的情况进行处理
            if (chars[i] == '.') {
                boolean flag =false;
                for (int j = 0; j < 26; j++) {
                    if(root.child[j]!=null) {
                       if(find(root.child[j],word.substring(i+1))){//如果遇到'.' 对后方递归 由于可能有多个word匹配 故这里需要对前26个进行循环 如果有一个满足条件便返回true
                           flag = true;
                        }
                    }
                }
                return flag;
            } else {
                if (root.child[index] == null&&root.child[26]==null) { //如果既不是通配符也不匹配
                    return false;
                }
                else
                {
                    if(root.child[26]!=null) //如果之前是通配符 将root置为通配符
                    {
                        root = root.child[26];
                    }
                    else
                    {
                        root = root.child[index];
                    }
                }
            }
        }
        return root.isleaf; //返回字典树中是否存在该word
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值