leetcode 力扣 208 前缀树Trie

96 阅读1分钟

我的建议是直接看图

非常巧妙的一道题,这道题的关键是在数组中构造数节点,使用含26个树节点的数组保存字母,当然不是直接保存字母,而是将char转换为int,使用数组下标保存

insert操作中,每次完整地输入一个单词后,都将末尾节点的isEnd标记为true,表示这是该单词的结尾,用于search操作判断当前查询的word是否存在于树中,例如当树中只有’apple‘,如果search ’app‘则会返回false,因为e节点的isEnd == true,而p节点的isEnd == false

lc208_1.jpeg

lc208_2.jpeg

lc208_3.jpeg

lc208_4.jpeg

class Trie {

    private boolean isEnd;
    Trie[] next;

    public Trie() {
        isEnd = false;
        next = new Trie[26];
    }
    
    public void insert(String word) {
        Trie node = this;
        for(char c : word.toCharArray())
        {
            if(node.next[c - 'a'] == null){
                node.next[c - 'a'] = new Trie();
            }

            node = node.next[c - 'a'];
        }

        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = this;
        for(char c : word.toCharArray())
        {
            if(node.next[c - 'a'] == null){
                return false;
            }

            node = node.next[c - 'a'];
        }

        return node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        Trie node = this;
        for(char c : prefix.toCharArray())
        {
            if(node.next[c - 'a'] == null){
                return false;
            }

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