栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

leecode 211-添加与搜索单词 - Trie和dfs - java实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leecode 211-添加与搜索单词 - Trie和dfs - java实现


本题的关键在于两点:首先是构造Trie,并实现相关add操作;其次是通过dfs来对整个Trie进行搜索和遍历,来进行匹配。
具体代码如下(Java实现,关于trie的相关知识,大家可以自行百度~)

public class Trie{
    public Trie[] children;
    public boolean isEnd;

    Trie(){
        this.children = new Trie[26];
        this.isEnd = false;
    }

    public void insert(String word){
        Trie root = this;
        for(char c : word.toCharArray()){
            if(root.children[c - 'a'] == null){
                root.children[c - 'a'] = new Trie();
            }
            root = root.children[c - 'a'];
        }
        root.isEnd = true;
    }
}

class WordDictionary {
    Trie T = new Trie();

    public WordDictionary() {

    }
    
    public void addWord(String word) {
        T.insert(word);
    }
    
    public boolean search(String word) {
        return dfs(word, T);
    }

    public boolean dfs(String word, Trie rt){
        // 递归终止条件
        if(word.length() == 0){
            return rt.isEnd;
        }

        // 第一个字符是字母
        if (word.charAt(0) != '.'){
            int ID = (int)(word.charAt(0) - 'a');
            if(rt.children[ID] != null){
                if(dfs(word.substring(1), rt.children[ID]) == true){
                    return true;
                }
            }
            return false;
        }

        // 第一个字符是.
        for(int ID=0;ID<26;ID++){
            if(rt.children[ID]!=null){
                if(dfs(word.substring(1), rt.children[ID]) == true){
                    return true;
                }
            }
        }

        
        return false;
    }
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337447.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号