前缀树的实现(Java)

前缀树

——实现动态插入或查询单词

class TrieNode {
    public TrieNode[] children;
    boolean hasWord;
    
    public TrieNode(){
        children = new TrieNode[26];
        hasWord = false; //判断是否为完整的单词
    }
}

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

    /*
     * @param word: a word
     * @return: nothing
     */
    public void insert(String word) {
        // write your code here
        TrieNode T = root;
        char[] ch = word.toCharArray();
        for(char c:ch){
            int a = c - 'a';
            if(T.children[a] == null){
                T.children[a] = new TrieNode();
            }
            T = T.children[a];
        }
        T.hasWord = true;
    }

    /* 查询单词
     * @param word: A string
     * @return: if the word is in the trie.
     */
    public boolean search(String word) {
        // write your code here
        TrieNode T = root;
        char[] ch = word.toCharArray();
        for(char c:ch){
            int a = c - 'a';
            if(T.children[a] == null){
                return false;
            }
            T = T.children[a];
        }
        return T.hasWord;
    }

    /* 查询单词前缀
     * @param prefix: A string
     * @return: if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        // write your code here
        // write your code here
        TrieNode T = root;
        char[] ch = prefix.toCharArray();
        for(char c:ch){
            int a = c - 'a';
            if(T.children[a] == null){
                return false;
            }
            T = T.children[a];
        }
        return true;
    }
}

你可能感兴趣的:(Java,算法)