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

目录

一、题目描述

二、思路讲解及代码实现

        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] 的二十六叉前缀树长这样(没出现的字母的叉就没画出来):

 

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);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值