首页 > 其他分享 >208. Implement Trie (Prefix Tree)[Medium]

208. Implement Trie (Prefix Tree)[Medium]

时间:2023-02-14 13:11:55浏览次数:53  
标签:search Medium word cur val Trie 208 app trie

208. Implement Trie (Prefix Tree)

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • Trie() Initializes the trie object.
  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

Constraints:

  • 1 <= word.length, prefix.length <= 2000
  • word and prefix consist only of lowercase English letters.
  • At most 3 * 10^4 calls in total will be made to insert, search, and startsWith.

Example

Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]

Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // return True
trie.search("app");     // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app");     // return True

思路

关键要知道前缀树的数据结构:一个Map来存后续字符,及对应的节点,和当前是否是结束位的标识

题解

class TrieNode {
        HashMap<Character, TrieNode> node = new HashMap<>();
        boolean isEnd;
    }

    TrieNode root = new TrieNode();

    public void insert(String word) {
        char[] data = word.toCharArray();
        TrieNode cur = root;
        for (char val : data) {
            if (!cur.node.containsKey(val))
                cur.node.put(val, new TrieNode());
            cur = cur.node.get(val);
        }
        cur.isEnd = true;
    }

    public boolean search(String word) {
        char[] data = word.toCharArray();
        TrieNode cur = root;
        for (char val : data) {
            if (!cur.node.containsKey(val))
                return false;
            cur = cur.node.get(val);
        }

        return cur.isEnd;
    }

    public boolean startsWith(String prefix) {
        char[] data = prefix.toCharArray();
        TrieNode cur = root;
        for (char val : data) {
            if (!cur.node.containsKey(val))
                return false;
            cur = cur.node.get(val);
        }

        return true;
    }

标签:search,Medium,word,cur,val,Trie,208,app,trie
From: https://www.cnblogs.com/tanhaoo/p/17119245.html

相关文章