[Leetcode] 208. Implement Trie (prefix tree)

Title description:

Insert picture description here

Java code:

//定义一个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);
 */

Previous blog: [Niuke.com] Xiaomi shopping (two points answer)

Guess you like

Origin blog.csdn.net/IAMLSL/article/details/114298342
Recommended