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

leetcode ----Trie专题

时间:2015-06-05 22:42:59      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:leetcode   trie   

一:Implement Trie (Prefix Tree)

题目:

Implement a trie with insertsearch, and startsWith methods.

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

分析:此题是典型的trie树,可以参见:http://blog.csdn.net/lu597203933/article/details/44227431

代码:

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

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

    // Inserts a word into the trie.
    void insert(string s) {
        TrieNode *p = root;
        for(int i = 0; i < s.size(); i++){
            if(p->next[s[i]-'a'] == NULL){
                p->next[s[i]-'a'] = new TrieNode();
            }
            p = p->next[s[i]-'a'];
        }
        p->isString = true;
    }

    // Returns if the word is in the trie.
    bool search(string key) {
        TrieNode *p = root;
        for(int i = 0; i < key.size(); i++){
            if(p == NULL) return false;
            p = p->next[key[i]-'a'];
        }
        if(p == NULL || p->isString == false) return false;
        return true;
        
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode *p = root;
        for(int i = 0; i <= prefix.size(); i++){
            if(p == NULL) return false;
            p = p->next[prefix[i]-'a'];
        }
        return true;
    }

private:
    TrieNode* root;
};

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


leetcode ----Trie专题

标签:leetcode   trie   

原文地址:http://blog.csdn.net/lu597203933/article/details/46382041

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