实现前缀树 Implement Trie (Prefix Tree)

问题:

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

解决:https://www.cnblogs.com/grandyang/p/4491665.html

【题意】实现字典树(前缀树),这道题让我们实现一个重要但又有些复杂的数据结构-字典树, 又称前缀树或单词查找树,例如,一个保存了8个键的trie结构,"A", "to", "tea", "ted", "ten", "i", "in", and "inn".如下图所示:

实现前缀树 Implement Trie (Prefix Tree)

字典树主要有如下三点性质:

1. 根节点不包含字符,除根节点以外每个节点只包含一个字符

2. 从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串

3. 每个节点的所有子节点包含的字符串不相同

① 一个字典树的节点应该包含字母,其子节点,以及标记其是否为叶节点的标记位。

class TrieNode{//209ms
    char c;//当前节点的字符
    Map<Character,TrieNode> children = new HashMap<>();//子节点
    boolean isLeaf;//标记是否为叶节点
    public TrieNode(){}
    public TrieNode(char c){
        this.c = c;
    }
}
public class Trie{
    private TrieNode root;
    public Trie(){
        root = new TrieNode();//初始化根节点
    }
    public void insert(String word){
        Map<Character,TrieNode> cur = root.children;//获取根节点的子节点,从它开始加入
        for (int i = 0;i < word.length() ;i ++ ) {
            char c = word.charAt(i);
            TrieNode tmp;
            if (cur.containsKey(c)) {
                tmp = cur.get(c);//获取插入的节点
            }else{
                tmp = new TrieNode(c);
                cur.put(c,tmp);
            }
            cur = tmp.children;
            if (i == word.length() - 1) {
                tmp.isLeaf = true;
            }
        }
    }
    public boolean search(String word){
        TrieNode tmp = searchNode(word);//查找前缀,并返回叶节点
        if (tmp != null && tmp.isLeaf) {
            return true;
        }else{
            return false;
        }
    }
    public boolean startsWith(String prefix){
        if (searchNode(prefix) == null) {
            return false;
        }else{
            return true;
        }
    }
    public TrieNode searchNode(String str){//查找前缀
        Map<Character,TrieNode> cur = root.children;
        TrieNode tmp = null;
        for (int i = 0;i < str.length() ;i ++ ) {
            char c = str.charAt(i);
            if (cur.containsKey(c)) {
                tmp = cur.get(c);
                cur = tmp.children;
            }else{
                return null;
            }
        }
        return tmp;
    }
}

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

② 使用数组提高性能。

每个trie节点只能包含'a' - 'z'字符。 所以我们可以使用一个数组来存储这个字符。

class TrieNode{//174ms
    TrieNode[] children;//每个节点用一个大小为26的数组表示,因为小写字母范围为a-z
    boolean isLeaf;
    public TrieNode(){
        children = new TrieNode[26];//初始化节点
    }
}
public class Trie{
    private TrieNode root;
    public Trie(){
        root = new TrieNode();//初始化根节点
    }
    public void insert(String word){
        TrieNode cur = root;
        for (int i = 0;i < word.length() ;i ++ ) {
            char c = word.charAt(i);
            int index = c - 'a';
            if (cur.children[index] != null) {
                cur = cur.children[index];
            }else{
                TrieNode tmp = new TrieNode();
                cur.children[index] = tmp;
                cur = tmp;
            }
        }
        cur.isLeaf = true;
    }
    public boolean search(String word){
        TrieNode tmp = searchNode(word);//查找前缀,并返回最后一个字符所在的节点
        if (tmp != null && tmp.isLeaf) {
            return true;
        }
        return false;
    }
    public boolean startsWith(String prefix){
        if (searchNode(prefix) == null) {
            return false;
        }else{
            return true;
        }
    }
    public TrieNode searchNode(String str){
        TrieNode cur = root;
        for (int i = 0;i < str.length() ;i ++ ) {
            char c = str.charAt(i);
            int index = c - 'a';
            if (cur.children[index] != null) {
                cur = cur.children[index];
            }else{
                return null;
            }
        }
        if (cur == root) {
            return null;
        }
        return cur;
    }
}
/**
 * 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);
 */

③ 将TrieNode作为内部类。

class Trie{ //160ms
    class TrieNode{
        TrieNode[] children;
        boolean isLeaf;
        public TrieNode(){
            children = new TrieNode[26];
            isLeaf = false;
        }
    }
    private TrieNode root;
    public Trie(){
        root = new TrieNode();
    }
    public void insert(String word){
        TrieNode cur = root;
        char[] wchar = word.toCharArray();
        for (int i = 0;i < word.length() ;i ++ ) {
            if (cur.children[wchar[i] - 'a'] != null) {
                cur = cur.children[wchar[i] - 'a'];
            }else{
                TrieNode tmp = new TrieNode();
                cur.children[wchar[i] - 'a'] = tmp;
                cur = tmp;
            }
        }
        cur.isLeaf = true;
    }
    public boolean search(String word){
        char[] wchar = word.toCharArray();
        TrieNode cur = root;
        for (int i = 0;i < word.length() ;i ++ ) {
            if (cur.children[wchar[i] - 'a'] == null) {
                return false;
            }else{
                cur = cur.children[wchar[i] - 'a'];
            }
        }
        return cur.isLeaf;
    }
    public boolean startsWith(String word){
        if (word.length() == 0) {
            return true;
        }
        char[] wchar = word.toCharArray();
        TrieNode cur = root;
        for (int i = 0;i < word.length() ;i ++ ) {
            if (cur.children[wchar[i] - 'a'] == null) {
                return false;
            }else{
                cur = cur.children[wchar[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);
 */

转载于:https://my.oschina.net/liyurong/blog/1575034