java 208.实现Trie(前缀树).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 208.实现Trie(前缀树).java相关的知识,希望对你有一定的参考价值。

class TrieNode{
    
    private TrieNode[] children;
    public boolean hasWord;
    
    public TrieNode() {
        children = new TrieNode[26];
        hasWord = false;
    }
    
    public void insert(String word, int index){
        if( index == word.length()){
            hasWord = true;
            return; 
        }
        
        int pos = word.charAt(index) - 'a';
        
        if(children[pos] == null){
            children[pos] = new TrieNode();
        } 
        
        children[pos].insert(word, index + 1);
    }
    
    public TrieNode find(String word, int index){
        if( index == word.length()){
            return this;
        }
        
        int pos = word.charAt(index) - 'a';
        
        if(children[pos] == null){
            return null;
        } 
        
        return children[pos].find(word, index + 1);
        
    }
}

public class Trie {
    
    private TrieNode root;
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        root.insert(word, 0);
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = root.find(word, 0);
        return node != null && node.hasWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = root.find(prefix, 0);
        return node != null;
    }
}

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

以上是关于java 208.实现Trie(前缀树).java的主要内容,如果未能解决你的问题,请参考以下文章

java 208.实现Trie(前缀树).java

java 208.实现Trie(前缀树).java

java 208.实现Trie(前缀树).java

java 208.实现Trie(前缀树).java

java刷题--208Trie前缀树

java刷题--208Trie前缀树