Implement Trie (Prefix Tree)

本文介绍了一种使用Trie树的数据结构来实现字符串的插入、搜索和前缀匹配的方法。通过递归的方式创建了一个Trie树节点类,并实现了插入、搜索及前缀匹配的功能。

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

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

思路:
之前也没有接触过Trie,百科上查了一下,大概就是词源的问题,N个word有公共前缀,只是后缀不同,可以用树表示。
可以通过递归解决。

代码如下:

class TrieNode {
    // 应该都是private的;只是为了减少代码量
    // Initialize your data structure here.
    public Map<Character,TrieNode> map;//存放后缀
    public char val;//当前节点的字符值
    public boolean tail;//一个字符串以该节点结尾
    public TrieNode() {
        map = new HashMap<>();
        tail=false;
    }
    public TrieNode(char c) {
        map = new HashMap<>();
        this.val=c;
        tail=false;
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        insert(root,word);
    }

    private void insert(TrieNode root,String word){
        if(word.length()==0){
            root.tail=true;
            return;
        }
        TrieNode cur=root;
        char c=word.charAt(0);
        if(cur.map.containsKey(c)){
            TrieNode child = cur.map.get(c);
            insert(child,word.substring(1));
        }else{
            TrieNode child = new TrieNode(c);
            cur.map.put(c,child);
            insert(child,word.substring(1));
        }
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        return search(root,word);
    }

    private boolean search(TrieNode root,String word){
        if(word.length()==0)
            return root.tail==true;
        char c = word.charAt(0);
        if(!root.map.containsKey(c))
            return false;
        TrieNode child = root.map.get(c);
        return search(child,word.substring(1));
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
         return startsWith(root,prefix);
    }

    private boolean startsWith(TrieNode root,String prefix) {
        if(prefix.length()==0)
            return true;
        char c = prefix.charAt(0);
        if(!root.map.containsKey(c))
            return false;
        TrieNode child = root.map.get(c);
        return startsWith(child,prefix.substring(1));
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值