Algorithms—208.Implement Trie (Prefix Tree)

本文介绍了一种使用Java实现的Trie树数据结构。该结构支持字符串的插入、搜索及前缀匹配等功能,适用于自动补全、拼写检查等应用场景。

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

思路:构造一个最多有26叉的树,为了方便,用map装子树,增加一个布尔值标志,布尔值为真,表示至此节点,有一个单词,布尔值为假,表示此节点不是某个单词的最后一个字母。

class TrieNode {
    // Initialize your data structure here.
    Map<Character,TrieNode> sons=new HashMap<Character,TrieNode>();
    char val;
    boolean flag=false;
    public TrieNode(char x) {
        val=x;
    }
}

public class Trie {
    private TrieNode root;

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

    // Inserts a word into the trie.
    public void insert(String word) {
        if(!search(word)){
        	TrieNode tt=root;
            char[] ac=word.toCharArray();
            for(int i=0;i<ac.length;i++){
                Map<Character,TrieNode> sons=root.sons;
                if(sons.get(ac[i])==null){
                    TrieNode node=new TrieNode(ac[i]);
                    if(i==ac.length-1){
                        node.flag=true;
                    }
                    sons.put(ac[i],node);
                    root=node;
                }else{
                    root=sons.get(ac[i]);
                    if(i==ac.length-1){
                        root.flag=true;
                    }
                }
            }
            root=tt;
        }
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
    	TrieNode tt=root;
        char[] ac=word.toCharArray();
        for(int i=0;i<ac.length;i++){
            Map<Character,TrieNode> sons=root.sons;
            if(sons.get(ac[i])==null){
                root=tt;
                return false;
            }
            root=sons.get(ac[i]);
        }
        boolean ans=root.flag;
        root=tt;
        return ans;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
    	TrieNode tt=root;
        char[] ac=prefix.toCharArray();
        for(int i=0;i<ac.length;i++){
            Map<Character,TrieNode> sons=root.sons;
            if(sons.get(ac[i])==null){
                root=tt;
                return false;
            }
            root=sons.get(ac[i]);
        }
        root=tt;
        return true;
    }
}

// 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、付费专栏及课程。

余额充值