• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
208. Implement Trie (Prefix Tree) -- 键树

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

class TrieNode {
public:
    // Initialize your data structure here.
    bool isWord;
    unordered_map<char, TrieNode*> alpha;
    TrieNode():isWord(false) {}
};

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

    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode *p = root;
        int l = word.length(), i;
        for(i = 0; i < l; i++)
        {
            if(p->alpha.find(word[i]) == p->alpha.end())
            {
                TrieNode *t = new TrieNode();
                p->alpha[word[i]] = t;
            }
            p = p->alpha[word[i]];
        }
        p->isWord = true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode *p = root;
        int l = word.length(), i;
        for(i = 0; i < l; i++)
        {
            if(p->alpha.find(word[i]) == p->alpha.end())
                return false;
            p = p->alpha[word[i]];
        }
        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;
        int l = prefix.length(), i;
        for(i = 0; i < l; i++)
        {
            if(p->alpha.find(prefix[i]) == p->alpha.end())
                return false;
            p = p->alpha[prefix[i]];
        }
        return true;
    }

private:
    TrieNode* root;
};

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

 

posted on 2016-04-21 14:52  ArgenBarbie  阅读(178)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3