LeetCode.208 前缀树

LeetCode.208 前缀树

class Trie {
    private final int MAX_LEN = 26;
    private boolean isEnd = false;
    private Trie[] next = new Trie[MAX_LEN]; // 定义一个以Trie为对象的数组

    /** Initialize your data structure here. */
    public Trie() {
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        Trie root = this; // 获取前最缀树的根节点
        for (int i = 0; i < word.length(); i++) {
            if (root.next[word.charAt(i) - 'a'] == null) { // 当前字符对应的前缀树的节点为空
                root.next[word.charAt(i) - 'a'] = new Trie(); // 新建一个对象插入到前缀树的节点中
            }
            root = root.next[word.charAt(i) - 'a'];
        }
        root.isEnd = true; // 当字符全部插入到前缀树中,标记最后一个字符在前缀树中的flag为True。此外,其余字符在前缀树中的flag为False。
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Trie root = this;
        for (int i = 0; i < word.length(); i++) {
            if (root.next[word.charAt(i) - 'a'] == null) {
                return false;
            }
            root = root.next[word.charAt(i) - 'a'];
        }
        return root.isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Trie root = this;
        for (int i = 0; i < prefix.length(); i++) {
            if (root.next[prefix.charAt(i) - 'a'] == null) {
                return false;
            }
            root = root.next[prefix.charAt(i) - '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);
 */

将单词插入前缀树示例:
将单词插入前缀树示例

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值