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

LeetCode "Add and Search Word - Data structure design"

时间:2015-05-20 02:04:05      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

I‘m glad to see that LeetCode has finally realized the importance of Trie.

My C++ code can be further optimized..

技术分享
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 WordDictionary {
public:
    WordDictionary() 
    {
        root = new TrieNode();
    }
    
    ~WordDictionary()
    {
        if (root)    delete root;
    }
    // Adds a word into the data structure.
    void addWord(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 data structure. A word could
    // contain the dot character ‘.‘ to represent any one letter.
    bool search(string key) {
        return _search(key, *root);
    }

private:
    bool _search(string sub, TrieNode &r)
    {
        if(sub.empty()) return true;
        if(sub.length() == 1)
        {
            if (sub[0] == .)
            {
                for (auto &n : r.childMap)
                    if(n.second.bIsLast) 
                        return true;
                return false;
            }
            else 
            {
                return r.childMap.find(sub[0]) != r.childMap.end() && r.childMap[sub[0]].bIsLast;
            }
        }

        for(int i = 0; i < sub.length(); i ++)
        {
            char c = sub[i];
            string ss = sub.substr(i + 1);
            if (c == .)
            {
                for (auto &n : r.childMap)
                    if(_search(ss, n.second)) 
                        return true;
                return false;
            }
            else        
            {
                if(r.childMap.find(c) != r.childMap.end())
                    return _search(ss, r.childMap[c]);                    
                
                return false;
            }
        }
        
        return false;
    }
    TrieNode* root;
};
View Code

LeetCode "Add and Search Word - Data structure design"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4516111.html

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