【leetcode】 208. 实现 Trie (前缀树)

题目描述:

在这里插入图片描述

Java代码:

//定义一个trie的结点类TrieNode,其成员变量有一个布尔型的isWord及TrieNode型的数组,相当于一个多叉树
//isWord为true时表示该结点是一个单词的结尾
//TrieNode型的数组用于指向其它代表字母的TrieNode结点
class TrieNode{
   boolean isWord;   
   TrieNode [] next;
    TrieNode(){
    isWord=false;
    next=new TrieNode[26];
    }
}

class Trie {
  /** Initialize your data structure here. */
    TrieNode root;   //一个根结点代表了一棵trie树(前缀树),根节点并不存储任何字母
    public Trie() {
    root=new TrieNode();   
    }
    /** Inserts a word into the trie. */
    //遍历word的每个字母,若之前未在当前结点插入当前字母,就申请一个TrieNode结点,然后像建链表一样往下加结点。
    public void insert(String word) {  
    TrieNode pr=this.root;
    int n=word.length();
    for(int i=0;i<n;i++){
    char c=word.charAt(i); 
    if(pr.next[c-'a']==null){
    TrieNode node=new TrieNode();
    pr.next[c-'a']=node;    
    }
    pr=pr.next[c-'a'];
    }
    pr.isWord=true;       //末尾的单词做一个标记
    }
    
    /** Returns if the word is in the trie. */
    //和建Trie类似,如果还未创建Trie中的某个结点或者末尾结点不是单词的结尾则表示没有这个word
    public boolean search(String word) {
    TrieNode pr=this.root;
    int n=word.length();
    for(int i=0;i<n;i++){
    char c=word.charAt(i); 
    if(pr.next[c-'a']==null)
    return false;
    pr=pr.next[c-'a'];
    }
    return  pr.isWord; 
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    //查前缀和查单词的区别仅在于查前缀只要之前创建了结点就存在前缀,而单词一定要满足最后一个字母对应结点的isWord为true
    public boolean startsWith(String prefix) {
    TrieNode pr=this.root;
     int n=prefix.length();
    for(int i=0;i<n;i++){
    char c=prefix.charAt(i); 
    if(pr.next[c-'a']==null)
    return false;
    pr=pr.next[c-'a'];
    }
    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
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值