Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Implementation problem.

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode() {
        c = 0;
        bIsLast = false;
    }
    TrieNode(char vc) {
        c = vc;
        bIsLast = false;
    }
public:
    char c;
    bool bIsLast;
    map<char, TrieNode> childMap;
};

class Trie {
public:
    Trie() 
    {
        root = new TrieNode();
    }
    
    ~Trie()
    {
        if (root)
            delete root;
    }
    
    // Inserts a word into the trie.
    void insert(string s) {
        TrieNode *r = root;
        for (int i = 0; i < s.length(); i++)
        {
            if (r->childMap.find(s[i]) == r->childMap.end())
            {
                r->childMap.insert(make_pair(s[i], TrieNode(s[i])));
            }
            
            r = &(r->childMap[s[i]]);            
        }
        r->bIsLast = true;
    }

    // Returns if the word is in the trie.
    bool search(string key) {
        TrieNode *r = root;
        for (int i = 0; i < key.length(); i++)
        {
            if (r->childMap.find(key[i]) == r->childMap.end())
            {
                return false;
            }

            r = &(r->childMap[key[i]]);
        }

        return r->bIsLast;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode *r = root;
        for (int i = 0; i < prefix.length(); i++)
        {
            if (r->childMap.find(prefix[i]) == r->childMap.end())
            {
                return false;
            }

            r = &(r->childMap[prefix[i]]);
        }
        return true;
    }

private:
    TrieNode* root;
};
posted on 2015-05-13 13:28  Tonix  阅读(263)  评论(0编辑  收藏  举报