leetcode Add and Search Word - Data structure design

本文介绍了一种使用前缀树(Trie)的数据结构来实现单词字典的方法,该方法支持单词的添加和搜索功能,特别是能够处理包含通配符'.'的模式匹配。

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

题目链接

思路:
就是前缀树。如果碰到点符号就遍历好了,只要有一个返回true就返回true。。

class TrieNode {
    // Initialize your data structure here.
    TrieNode charecters[];
    boolean end;
    public TrieNode() {
        charecters=new TrieNode[26];
        end=false;
    }
}



public class WordDictionary {



    private TrieNode root;

    public WordDictionary() {
        root = new TrieNode();
        root.charecters=new TrieNode[26]; 
    }



    // Adds a word into the data structure.
    public void addWord(String word) {

        int n=word.length();
        TrieNode temp=root;
        for(int i=0;i<n;i++)
        {

            if(temp.charecters[word.charAt(i)-'a']==null)
            {
                temp.charecters[word.charAt(i)-'a']=new TrieNode();
            }
            temp=temp.charecters[word.charAt(i)-'a'];

        }
        temp.end=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 searchHelp(word, 0,root);
    }

    public boolean searchHelp(String word,int currentIndex,TrieNode root)
    {
        if(currentIndex==word.length())
        {
            return root.end==true;
        }
        char targetChar=word.charAt(currentIndex);
        if(targetChar=='.')
        {
            for(int i=0;i<26;i++)
            {

                if(root.charecters[i]!=null&&searchHelp(word, currentIndex+1, root.charecters[i]))
                {
                    return true;
                }

            }


        }
        else
        {
            if(root.charecters[targetChar-'a']!=null)
            {
                return searchHelp(word, currentIndex+1, root.charecters[targetChar-'a']);
            }

        }



        return false;

    }
}

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值