LeetCode-208. Implement Trie (Prefix Tree) [C++][Java]

LeetCode-208. Implement Trie (Prefix Tree)Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/implement-trie-prefix-tree/

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.

Example 1:

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

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 insertsearch, and startsWith.

【C++】

class TrieNode {
public:
    TrieNode* childNode[26];
    bool isVal;
    TrieNode(): isVal(false) {
        for (int i = 0; i < 26; ++i) {
            childNode[i] = nullptr;
        }
    }
};

class Trie {
    TrieNode* root;
public:
    Trie(): root(new TrieNode()) {}
    
    void insert(string word) {
        TrieNode* temp = root;
        for (int i = 0; i < word.size(); ++i) {
            if (!temp->childNode[word[i] - 'a']) {
                temp->childNode[word[i] - 'a'] = new TrieNode();
            }
            temp = temp->childNode[word[i] - 'a'];
        }
        temp->isVal = true;
    }
    
    bool search(string word) {
        TrieNode* temp = root;
        for (int i = 0; i < word.size(); ++i) {
            if (!temp) {break;}
            temp = temp->childNode[word[i] - 'a'];
        }
        return temp ? temp->isVal: false;
    }
    
    bool startsWith(string prefix) {
        TrieNode* temp = root;
        for (int i = 0; i < prefix.size(); ++i) {
            if (!temp) { break;}
            temp = temp->childNode[prefix[i] - 'a'];
        }
        return temp;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

【Java】

class Trie {
    private TrieNode root;
    
    private class TrieNode {
        public TrieNode[] mChildNode = new TrieNode[26];
        public boolean mIsVal = false;
        
        public TrieNode() {
            for (int i = 0; i < 26; ++i) {
                mChildNode[i] = null;
            }
        }
    }

    public Trie() {
        root = new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode temp = root;
        for (int i = 0; i < word.length(); ++i) {
            if (temp.mChildNode[word.charAt(i) - 'a'] == null) {
                temp.mChildNode[word.charAt(i) - 'a'] = new TrieNode();
            }
            temp = temp.mChildNode[word.charAt(i) - 'a'];
        }
        temp.mIsVal = true;
    }
    
    public boolean search(String word) {
        TrieNode temp = root;
        for (int i = 0; i < word.length(); ++i) {
            if (temp == null) {break;}
            temp = temp.mChildNode[word.charAt(i) - 'a'];
        }
        return temp != null ? temp.mIsVal : false;
    }
    
    public boolean startsWith(String prefix) {
        TrieNode temp = root;
        for (int i = 0; i < prefix.length(); ++i) {
            if (temp == null) {break;}
            temp = temp.mChildNode[prefix.charAt(i) - 'a'];
        }
        return temp != null;
    }
}

/**
 * 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);
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值