码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode208:Implement Trie (Prefix Tree)

时间:2015-07-03 17:35:14      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

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

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

Hide Tags Data Structure Trie

实现一棵Trie树以及实现查询的功能,根据上一篇文章中的分析和伪代码可以很迅速地实现:
runtime:68ms

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode() {
            words=0;
            prefixs=0;
            for(int i=0;i<26;i++)
               edges[i]=NULL; 
        }
        int words;
        int prefixs;
        TrieNode* edges[26];
};

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

    // Inserts a word into the trie.
    void insert(string word) {
            insertHelper(root,word,0);
    }

    // Returns if the word is in the trie.
    bool search(string word) {
            return searchHelper(root,word,0)!=0;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
            return startsWithHelper(root,prefix,0)!=0;
    }

    void insertHelper(TrieNode * node,string &word,int pos) {
        if(pos==word.size())
        {
            node->words++;
            node->prefixs++;
        }
        else
        {
            node->prefixs++;
            int char_code=word[pos]-‘a‘;
            if(node->edges[char_code]==NULL)
                node->edges[char_code]=new TrieNode();
            insertHelper(node->edges[char_code],word,pos+1);
        }
    }

    int searchHelper(TrieNode * node,string &word,int pos)
    {
        int char_code=word[pos]-‘a‘;
        if(pos==word.size())
            return node->words;
        else if(node->edges[char_code]==NULL)
            return 0;
        else 
            return searchHelper(node->edges[char_code],word,pos+1);
    }

    int startsWithHelper(TrieNode * node,string &word,int pos)
    {
        int char_code=word[pos]-‘a‘;
        if(pos==word.size())
            return node->prefixs;
        else if(node->edges[char_code]==NULL)
            return 0;
        else
            return startsWithHelper(node->edges[char_code],word,pos+1);
    }

private:
    TrieNode* root;
};

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode208:Implement Trie (Prefix Tree)

标签:

原文地址:http://blog.csdn.net/u012501459/article/details/46742505

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!