leetcode 前缀树(trie树)

public class Trie {

    /**
     * Initialize your data structure here.
     */
    boolean isword;
    HashMap<Character, Trie> next;

    public Trie() {
        isword = false;
        next = new HashMap<Character, Trie>();
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        Trie tp = this;
        for (int i = 0; i < word.length(); i++) {
            if (tp.next.containsKey(word.charAt(i))) {
                tp = tp.next.get(word.charAt(i));
            } else {
                Trie t = new Trie();
                tp.next.put(word.charAt(i), t);
                tp = t;
            }
        }
        tp.isword = true;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        Trie tp = this;
        for (int i = 0; i < word.length(); i++) {
            if (tp.next.containsKey(word.charAt(i))) {
                tp = tp.next.get(word.charAt(i));
            } else {
                return false;
            }
        }
        return tp.isword;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        Trie tp = this;
        for (int i = 0; i < prefix.length(); i++) {
            if (tp.next.containsKey(prefix.charAt(i))) {
                tp = tp.next.get(prefix.charAt(i));
            } else {
                return false;
            }
        }
        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);
 */

    原文作者:Trie树
    原文地址: https://blog.csdn.net/u010867294/article/details/77449778
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞