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

本文详细解析了LeetCode第211题Add and Search Word - Data structure design的解决方案,通过字典树(Trie)和递归实现单词的添加和搜索功能。介绍了字典树的基本操作,如何添加单词并维护节点状态,以及如何进行模式匹配,特别关注了通配符'. '的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题目链接
题目

在这里插入图片描述

解析

首先知道字典树的基本操作
对于这个题目:

  • addWord()操作没什么好说的,就是向字典树添加元素,记得维护结点的end值;
  • 匹配的过程是一个递归的过程,从根结点开始,递归终止条件是node.end > 0(返回(也就是是否有));
  • 对于匹配操作要分两种情况,如果不是'.',就定位到该匹配的子树,继续递归匹配;
  • 如果是'.',就要遍历该结点的所有next[i],去搜索匹配,这些next[i]中只要有一个匹配成功就返回true,否则返回false

在这里插入图片描述

class WordDictionary {
    
    private class Node {
        public int end;
        public Node[] next;//使用整数表示字符 c - 'a'

        public Node() {
            end = 0;
            next = new Node[26];
        }
    }

    private Node root;

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

    public void addWord(String word) {
        if (word == null)
            return;
        Node cur = root;
        int index;
        for (int i = 0; i < word.length(); i++) {
            index = word.charAt(i) - 'a';
            if (cur.next[index] == null)
                cur.next[index] = new Node();
            cur = cur.next[index];
        }
        cur.end++;
    }

    public boolean search(String word) {
        return process(root, word, 0);
    }

    public boolean process(Node node, String word, int index) {
        if (node == null)
            return false;
        if (index == word.length())
            return node.end > 0;
        char c = word.charAt(index);
        if (c != '.') {
            int idx = c - 'a';
            if (node.next[idx] == null)
                return false;
            else {
                return process(node.next[idx], word, index + 1);
            }
        } else {  // c == '.' search all the subTree
            for (Node cur : node.next) {
                if (process(cur, word, index + 1))
                    return true;
            }
            return false;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值