其他分享
首页 > 其他分享> > May LeetCoding Challenge14 之 字典树

May LeetCoding Challenge14 之 字典树

作者:互联网

字典树结点结构:

class Node{

boolean isWord;

TreeMap<Character, Node> next;

}

字典树的应用:

1.自动补全 2.拼写检查 3.IP 路由 4.预测文字

字典树的局限:

空间占用大。优化方法有压缩字典树。

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

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

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

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

 JAVA

class Trie {
    private class Node{
        public boolean isWord;
        public TreeMap<Character, Node> next;
        public Node(boolean isWord){
            this.isWord = isWord;
            next = new TreeMap<>();
        }
        public Node(){
            this(false);//this关键字调用重载构造方法,且必须位于构造方法的第一句
        }
    };
    private Node root;

    /** Initialize your data structure here. */
    public Trie() {
        root = new Node();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        Node cur = root;
        for(char c: word.toCharArray()){
            if(cur.next.get(c) == null){
                cur.next.put(c, new Node());
            }
            cur = cur.next.get(c);
        }
        cur.isWord = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Node cur = root;
        for(char c: word.toCharArray()){
            if(cur.next.get(c) == null)
                return false;
            cur = cur.next.get(c);
        }
        return cur.isWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Node cur = root;
        for(char c: prefix.toCharArray()){
            if(cur.next.get(c) == null)
                return false;
            cur = cur.next.get(c);
        }
        return true;
    }
}

 

Python3

 

标签:Node,LeetCoding,word,cur,May,next,Challenge14,public,isWord
来源: https://www.cnblogs.com/yawenw/p/12891349.html