• [LeetCode-JAVA] Implement Trie (Prefix Tree)


    题目:

    Implement a trie with insertsearch, and startsWith methods.

    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.insert("somestring");
    // trie.search("key");

    思路:

    题目的内容是实现一个前缀树,用来存储string的,因此可以理解为一个26叉树,为了保存每一个节点的孩子,用hashmap来进行储存。

    同时回顾前缀树的概念,除了内容为一个字符外,每一个节点还应有一个标志位,是否为已经查过的(即添加的)单词。

    insert:分析单词的每一个字符,如果存在与已经有的孩子中,则循环转到该孩子节点,否则新建孩子节点,最后在单词的末尾字符isWord标志位true;

    search: 逐个分析每个字符,如果不存在该字符的孩子则返回false,否则循环之后,查看末尾字符的标志位即可;

    pifix: 和search一样,只是在最后只要是都存在每个字符相应的孩子map,则返回true。

    代码:

    class TrieNode {
        // Initialize your data structure here.
        boolean isWord;
        HashMap<Character, TrieNode> map;
        public TrieNode() {
            map = new HashMap<Character, TrieNode>();
        }
    }
    
    public class Trie {
        private TrieNode root;
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            char[] charray = word.toCharArray();
            TrieNode temp = root;
            for(int i = 0 ; i < charray.length ; i++){
                if(!temp.map.containsKey(charray[i]))
                    temp.map.put(charray[i], new TrieNode()); //添加
                temp = temp.map.get(charray[i]); //转到孩子节点
                if(i == charray.length - 1) //末尾字符
                    temp.isWord = true;
            }
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode temp = root;
            
            for(int i = 0 ; i < word.length() ; i++){
                TrieNode next = temp.map.get(word.charAt(i));
                if(next == null)
                    return false;
                temp = next;
            }
            return temp.isWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode temp = root;
            
            for(int i = 0 ; i < prefix.length() ; i++){
                TrieNode next = temp.map.get(prefix.charAt(i));
                if(next == null)
                    return false;
                temp = next;
            }
            return true;
        }
    }

    参考链接:http://www.bubuko.com/infodetail-807921.html

  • 相关阅读:
    Mechanism of Loading Resources
    Dashboards (Android)
    Tips: compilation and creating new projects on Android 4.0
    设备方向
    【转】字符串分割(C++)
    Moving From Objective-C to C++
    Simulate android behaviors on win32
    【ybtoj高效进阶 21265】排队问题(fhq-Treap)(构造)
    【ybtoj高效进阶 21262】头文字 D(线段树)(数学)
    【ybtoj高效进阶 21261】头文字 C(单调队列优化DP)
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4545631.html
Copyright © 2020-2023  润新知