力扣208:实现 Trie (前缀树) (Java多种数据结构)

人生之路不会是一帆风顺的,我们会遇上顺境,也会遇上逆境,在所有成功路上折磨你的,背后都隐藏着激励你奋发向上的动机,人生没有如果,只有后果与结果,成熟,就是用微笑来面对一切小事。

导读:本篇文章讲解 力扣208:实现 Trie (前缀树) (Java多种数据结构),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

目录

一、题目描述

二、思路讲解及代码实现

        1、数组实现

        2、哈希表实现

        3、哈希表优化时间

        4、二十六叉树 


一、题目描述

Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

  • Trie() 初始化前缀树对象。
  • void insert(String word) 向前缀树中插入字符串 word 。
  • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
  • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

示例:

输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]

解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // 返回 True
trie.search("app");     // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app");     // 返回 True

提示:

  • 1 <= word.length, prefix.length <= 2000
  • word 和 prefix 仅由小写英文字母组成
  • insertsearch 和 startsWith 调用次数 总计 不超过 3 * 104 次

二、思路讲解及代码实现

        1、数组实现

        将插入的字符串放入数组中,每次查找的时候都需要遍历一遍数组,时间上比较慢。 

class Trie {

    private List<String> list;

    public Trie() {
        list = new ArrayList<>();
    }
    
    public void insert(String word) {
        list.add(word);
    }
    
    public boolean search(String word) {
        for(String s : list) {
            if(s.equals(word)) {
                return true;
            }
        }
        return false;
    }
    
    public boolean startsWith(String prefix) {
        int len = prefix.length();
        for(String s : list) {
            if(len<=s.length() && s.substring(0, len).equals(prefix)) {
                return true;
            }
        }
        return false;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

        2、哈希表实现

        和用数组的思路差不多,只不过哈希表可以减少查询时候的复杂度。 

class Trie {

    private Map<String, Boolean> map;

    public Trie() {
        map = new HashMap<>();
    }
    
    public void insert(String word) {
        map.put(word, true);
    }
    
    public boolean search(String word) {
        return map.getOrDefault(word, false);
    }
    
    public boolean startsWith(String prefix) {
        Set<String> set = map.keySet();
        int len = prefix.length();
        for(String s : set) {
            if(len<=s.length() && s.substring(0, len).equals(prefix)) {
                return true;
            }
        }
        return false;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

        3、哈希表优化时间

        使用两个哈希表,一个存放单词本身,一个存放所有的前缀;查找单词的时候用第一个哈希表,查找前缀的时候用第二个哈希表。

class Trie {

    private Map<String, Boolean> map;
    private Map<String, Boolean> tri;

    public Trie() {
        map = new HashMap<>();
        tri = new HashMap<>();
    }
    
    public void insert(String word) {
        map.put(word, true);
        for(int i=1; i<=word.length(); i++) {
            tri.put(word.substring(0, i), true);
        }
    }
    
    public boolean search(String word) {
        return map.getOrDefault(word, false);
    }
    
    public boolean startsWith(String prefix) {
        return tri.getOrDefault(prefix, false);
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

        4、二十六叉树 

        我们知道,单词一共只有26种字母,那么我们用26叉树来表示所有单词的前缀。

class Trie {

    private boolean isEnd;      //该节点是否为末尾
    private Trie []children;    //二十六叉,0代表a,25代表z

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

        当出现一个字符时,我们就将对应的节点初始化。需要注意的是,每个节点的属性中是没有对应字母的值的,而是通过其在数组中的位置来确定具体是哪个值。比如,children[3] 被初始化了,我们就认为存在字母d。比如出现“ab”,我们就先初始化root的children[0],再初始化 root 的 children[0] 的 children[1]。

        比如字符串集合[them, zip, team, the, app, that] 的二十六叉前缀树长这样(没出现的字母的叉就没画出来):

力扣208:实现 Trie (前缀树) (Java多种数据结构)

 

class Trie {

    private boolean isEnd;
    private Trie []children;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
        Trie node = this;
        for(Character ch : word.toCharArray()) {
            int index = ch - 'a';
            if(node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        //如果返回的有值,并且已经是结尾了
        return node!=null && node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix)!=null;
    }

    /**
        看word是否存在于前缀树中
            -如果存在,返回最后一个节点
            -如果不存在,返回null
     */
    private Trie searchPrefix(String word) {
        Trie node = this;
        for(Character ch : word.toCharArray()) {
            int index = ch-'a';
            if(node.children[index]==null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/124962.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!