208. 实现 Trie (前缀树) [中等]

142 阅读2分钟

题目

Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 wordboolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 falseboolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false
  • 来源:力扣(LeetCode)
  • 链接:leetcode.cn/problems/im…
  • 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法

思路

  • 需要一个标识表示是不是一个存在的已插入的字符串。

代码

class Trie {
    
    private Map<Character, Trie> children;
    private boolean end;
    private String value;

    public Trie() {
        children = new HashMap<>();
        end = false;
        value = null;
    }

    public void insert(String word) {
        int n = word.length();
        Map<Character, Trie> children = this.children;
        for (int i = 0; i < n; i++) {
            Character c = word.charAt(i);
            Trie trie = children.computeIfAbsent(c, key -> new Trie());
            if (i == n-1) {
                trie.end = true;
                trie.value = word;
            }
            children = trie.children;
        }
    }
    
    // 辅助方法
    private Trie searchPrefix(String prefix) {
        int n = prefix.length();
        Map<Character, Trie> children = this.children;
        Trie trie = null;
        for (int i = 0; i < n; i++) {
            Character c = prefix.charAt(i);
            trie = children.get(c);
            if (trie == null) {
                break;
            } else {
                children = trie.children;
            }
        }
        return trie;
    }

    public boolean search(String word) {
        Trie trie = searchPrefix(word);
        return trie != null && trie.end;
    }

    public boolean startsWith(String prefix) {
        Trie trie = searchPrefix(prefix);
        return trie != null;
    }
}

update20230512

class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
    }
    
    public void insert(String word) {
        Trie node = this;
        char[] str = word.toCharArray();
        for (int i = 0; i < str.length; i++) {
            int index = str[i] - 'a';
            Trie temp = node.children[index];
            if (temp == null) {
                temp = new Trie();
                node.children[index] = temp;
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = visit(word);
        return node != null && node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        Trie node = visit(prefix);
        return node != null;
    }

    private Trie visit(String prefix) {
        Trie node = this;
        char[] str = prefix.toCharArray();
        for (int i = 0; i < str.length; i++) {
            int index = str[i] - 'a';
            Trie temp = node.children[index];
            if (temp == null) {
                return null;
            }
            node = temp;
        }
        return node;
    }
}

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