首页 > 其他 > 详细

208. Implement Trie (Prefix Tree)

时间:2019-08-10 18:18:13      阅读:95      评论:0      收藏:0      [点我收藏+]

技术分享图片

class Node {
    final static int the_maxsize = 26;
    Node[] list = new Node[the_maxsize];
    char data;
    boolean isEnd = false;                                                 //用isEnd 代替isSelf  节约空间
}

class Trie {
    Node node = new Node();
    /** Initialize your data structure here. */
    public Trie() {}

    /** Inserts a word into the trie. */
    public void insert(String word) {
        Node temp = node;
        char[] c = word.toCharArray();
        for (int i = 0; i < c.length; i++) {
            int loc = c[i] - 'a';
            if (temp.list[loc] == null) {
                temp.list[loc] = new Node();
                temp.list[loc].data = c[i];
            }
            temp = temp.list[loc];
        }
        temp.isEnd = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        if (word == null)
            return false;
        Node temp = node;
        char[] c = word.toCharArray();
        for (int i = 0; i < c.length; i++) {
            int loc = c[i] - 'a';
            if (temp.list[loc] != null)  temp = temp.list[loc];
            else return false;
        }
        if (temp.isEnd ) return true;
        else return false;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        Node temp = node;
        char[] c = prefix.toCharArray();
        for (int i = 0; i < c.length; i++) {
            int loc = c[i] - 'a';
            if (temp.list[loc] != null)
                temp = temp.list[loc];
            else
                return false;
        }
        return true;
    }
}

208. Implement Trie (Prefix Tree)

原文:https://www.cnblogs.com/cznczai/p/11332208.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!