Implement Trie

要点:

1)先建立Trienode;

2)再建立TrieTree;

code


class TrieNode {
public:
    // Initialize your data structure here.
    char c;
    map<char, TrieNode*> hash;
    bool isWord;

    TrieNode() {
        isWord = false;
    }

    TrieNode(char c)
    {
        this->c = c;
        isWord = false;
    }

};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode* p = root;
        for(int i = 0; i<word.length(); i++)
        {
            char c = word[i];

            if(p->hash.find(c) != p->hash.end())
            {
                p = p->hash[c];
            }
            else
            {
                TrieNode* newnode = new TrieNode(c);
                p->hash[c] = newnode;
                p = newnode;
            }

            if(i == word.length()-1)
            {
                p->isWord = true;
            }
        }
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode* p = root;
        for(char c : word)
        {
            if(p->hash.find(c) == p->hash.end())
            {
                return false;
            }
            else
            {
                p = p->hash[c];
            }
        }

        return p->isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode* p = root;
        for(char c : prefix)
        {
            if(p->hash.find(c) == p->hash.end())
            {
                return false;
            }
            else
            {
                p = p->hash[c];
            }
        }

        return true;
    }

private:
    TrieNode* root;
};

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

results matching ""

    No results matching ""