MENU

LeetCode208. 实现 Trie (前缀树)

August 9, 2018 • Read: 247 • LeetCode

题目链接:LeetCode208

题解

板子题

代码
class Trie {
    class TrieNode {
        public int end;
        public TrieNode[] nexts;
        public TrieNode() {
            end = 0;
            nexts = new TrieNode[26];
        }
    }
    TrieNode root = new TrieNode();
    
    /** Initialize your data structure here. */
    public Trie() {}
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        if(word == null) 
                return;
        char[] chs = word.toCharArray();
        TrieNode node = root;
        int index = 0;
        for(int i = 0;i < chs.length;i++) {
            index = chs[i] - 'a';
            if(node.nexts[index] == null)
                node.nexts[index] = new TrieNode();
            node = node.nexts[index];
        }   
        node.end++;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        char chs[] = word.toCharArray();
        TrieNode node = root;
        int index = 0;
        for(int i = 0;i < chs.length;i++) {
            index = chs[i] - 'a';
            if(node.nexts[index] == null)
                return false;
            node = node.nexts[index];
        }
        return node.end > 0;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        char[] chs = prefix.toCharArray();
        TrieNode node = root;
        int index = 0;
        for(int i = 0;i < chs.length;i++) {
            index = chs[i] - 'a';
            if(node.nexts[index] == null)
                return false;
            node = node.nexts[index];
        }
        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);
 */
最后编辑于: October 10, 2018
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment