208实现Trie (前缀树)-hot100-java

一、问题描述:

* 208实现Trie (前缀树)
* 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 仅由小写英文字母组成
* insert、search 和 startsWith 调用次数 总计 不超过 3 * 104 次

二、题解

对于leetcode平台,不能使用静态变量,

输入:

["Trie","insert","search","search","startsWith","insert","search"]
[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]
["Trie","startsWith"]
[[],["a"]]
["Trie","insert","insert","insert","insert","insert","insert","search","search","search","search","search","search","search","search","search","startsWith","startsWith","startsWith","startsWith","startsWith","startsWith","startsWith","startsWith","startsWith"]
[[],["app"],["apple"],["beer"],["add"],["jam"],["rental"],["apps"],["app"],["ad"],["applepie"],["rest"],["jan"],["rent"],["beer"],["jam"],["apps"],["app"],["ad"],["applepie"],["rest"],["jan"],["rent"],["beer"],["jam"]]

后面发现是因为全局变量使用了静态类型,于是不行,因为leetcode默认是无状态的.

也就是说不能这样写:

class Trie {
    public static Trie[] node = new Trie[26];
    public boolean isWord;

    public Trie() {
    }

    public void insert(String word) {
        char[] chars = word.toCharArray();
        Trie current  = this;
        Trie pre = null;
        int i = 0;
        for (; i < chars.length; i++) {
            pre = current;
            current = current.node[chars[i] - 97];
            if (current == null) break;
        }
        if (i == chars.length) {
            current.isWord = true;
            return;
        }

        for (int j = i; j < chars.length; j++) {
            pre.node[chars[j] - 97] = new Trie();
            pre = pre.node[chars[j] - 97];
        }
        pre.isWord = true;
    }

    public boolean search(String word) {
        Trie current = getPrefix(word);
        return current != null && current.isWord;
    }

    public boolean startsWith(String prefix) { return getPrefix(prefix) != null; }

    private Trie getPrefix(String prefix) {
        char[] chars = prefix.toCharArray();
        Trie current = this;

        for (int i = 0; i < chars.length; i++) {
            current = current.node[chars[i] - 97];
            if (current == null) return null;
        }
        return current;
    }
}

/**
 * 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);
 */

题解

class Trie {
    public Trie[] node ;
    public boolean isWord;

    public Trie() {
        node = new Trie[26];
    }

    public void insert(String word) {
        char[] chars = word.toCharArray();
        Trie current  = this;
        Trie pre = null;
        int i = 0;
        for (; i < chars.length; i++) {
            pre = current;
            current = current.node[chars[i] - 97];
            if (current == null) break;
        }
        if (i == chars.length) {
            current.isWord = true;
            return;
        }

        for (int j = i; j < chars.length; j++) {
            pre.node[chars[j] - 97] = new Trie();
            pre = pre.node[chars[j] - 97];
        }
        pre.isWord = true;
    }

    public boolean search(String word) {
        Trie current = getPrefix(word);
        return current != null && current.isWord;
    }

    public boolean startsWith(String prefix) { return getPrefix(prefix) != null; }

    private Trie getPrefix(String prefix) {
        char[] chars = prefix.toCharArray();
        Trie current = this;

        for (int i = 0; i < chars.length; i++) {
            current = current.node[chars[i] - 97];
            if (current == null) return null;
        }
        return current;
    }
}

/**
 * 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);
 */

对于成员变量也可以这样写,发现下面的效率更高:

class Trie {
    public Trie[] node = new Trie[26];
    public boolean isWord;

    public Trie() {
    }

    public void insert(String word) {
        char[] chars = word.toCharArray();
        Trie current  = this;
        Trie pre = null;
        int i = 0;
        for (; i < chars.length; i++) {
            pre = current;
            current = current.node[chars[i] - 97];
            if (current == null) break;
        }
        if (i == chars.length) {
            current.isWord = true;
            return;
        }

        for (int j = i; j < chars.length; j++) {
            pre.node[chars[j] - 97] = new Trie();
            pre = pre.node[chars[j] - 97];
        }
        pre.isWord = true;
    }

    public boolean search(String word) {
        Trie current = getPrefix(word);
        return current != null && current.isWord;
    }

    public boolean startsWith(String prefix) { return getPrefix(prefix) != null; }

    private Trie getPrefix(String prefix) {
        char[] chars = prefix.toCharArray();
        Trie current = this;

        for (int i = 0; i < chars.length; i++) {
            current = current.node[chars[i] - 97];
            if (current == null) return null;
        }
        return current;
    }
}

/**
 * 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);
 */

本地测试:

@Test
public void testSolution(){
    Trie trie = new Trie();
    trie.insert("apple");

    System.out.println(trie.search("apple")); // 返回 True
    System.out.println(trie.search("app"));// 返回 False
    System.out.println(trie.startsWith("app"));// 返回 T
    trie.insert("app");
    System.out.println(trie.search("app")); // 返回 True
}
@Test
public void testSolution2(){
    Trie trie = new Trie();
    System.out.println(trie.startsWith("a"));//F
}
@Test
public void testSolution3(){
    Trie trie = new Trie();
    trie.insert("hotdog");
    System.out.println(trie.startsWith("dog"));
}

2023.1.18三刷


class Trie {
    public boolean isEnd;
    public Trie[] next;
    public Trie() {
        next =new Trie[26];
    }
    
    public void insert(String word) {
        Trie cur = this;
        int index = -1;
        Trie curNext = null;//字面量因为每次都要改变,就放外边吧。
        for(char c : word.toCharArray()){//这里必定有递归的方式,但是感觉还是比较像node节点链表的形式,所以就这个循环里面写即可
            //这里不需要记录‘a’是97,无脑一点
            index = c - 'a';
            curNext = cur.next[index];
            if(curNext == null) {
                curNext = new Trie();
                cur.next[index] = curNext;
            }
            cur = curNext;
        }
        
        if(index != -1) cur.isEnd = true;//这里实际上不需要判断,因为index必定不为-1,因为word.length >= 1
    }
    
    public boolean search(String word) {
        Trie cur = this;
        int index = -1;
        for(char c : word.toCharArray()){
            index = c - 'a';
            cur = cur.next[index];
            if(cur == null) return false;
        }
        return cur.isEnd;
        
    }
    
    public boolean startsWith(String prefix) {
        Trie cur = this;
        int index = -1;
        for(char c : prefix.toCharArray()){
            index = c - 'a';
            cur = cur.next[index];
            if(cur == null) return false;
        }
        return true;
        
    }
}

/**
 * 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);
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值