Implementing Trie (prefix tree)

Implement a Trie (prefix tree), including insert, search, and startsWith.

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // Returns true
trie.insert("app");   
trie.search("app"); // returns true
Explain:

You can assume that all input is made up of lowercase letters a-z.
Ensure that all inputs are non-empty strings.
Have you met this question in a real interview?

Source: LeetCode
Link: https://leetcode-cn.com/problems/implementation-trie-prefix-tree
Copyright belongs to the seizure network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

 

class Trie {
public:
    /** Initialize your data structure here. */
    set<string> myset;
    Trie() {
        
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        auto it = myset.find(word);
        if(it == myset.end())
            myset.insert(word);
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        auto it = myset.find(word);
        if(it == myset.end())
            return  false;
        return  true;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
         for(auto it = myset.begin(); it != myset.end(); it++)
        {
            // std::size_t found = it->find(prefix);
            // if(found == 0)
            //     return true;
            string tmp = *it;
            std::size_t found = tmp.find(prefix);
            if(found == 0)
                 return true;
            //cout<<tmp<<endl;
        }
        return false;
    }
};

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

 

Tags: network

Posted on Mon, 07 Oct 2019 21:19:29 -0700 by shefali