LeetCode-Add and Search Word - Data structure design

题目链接:
https://leetcode.com/problems/add-and-search-word-data-structure-design/

题目非常直白,并没有什么拐弯抹角的地方,本身就是设计一个字典查询功能,可以实现简单的插入和搜索功能。

开始时,本不想设计太复杂的算法,心想用C++中的set集合或者map集合就可以。通过集合存储,查询时如果word中不包含.,那么直接查找返回即可时间O(1);如果包含.,就需要依次遍历字典中的word,查看是否正确匹配,时间O(n*m),其中n为字典中单词的个数,m为查询word的长度。

/**
 *   Description: https://leetcode.com/problems/add-and-search-word-data-structure-design/
 *        Author: zhaoxiaohui
 *          Site: zhaoxiaohui.sinaapp.com
 *          Date: 2015-11-15
 */
class WordDictionary {
public:
    set<string> words;
    // Adds a word into the data structure.
    void addWord(string word) {
        words.insert(word);
    }
    bool match_one(const char *word1, const char *word2) {
        while (word1 && word2) {
            if (*word1 != *word2) {
                return false;
            }
            word1++;
            word2++;
        }
        return true;
    }
    bool match(string &word, set<string> &words) {
        for (set<string>::iterator it =  words.begin(); it != words.end(); it++) {
            if (word.length() != it->length()) {
                continue;
            }
            if (match_one(word.c_str(), it->c_str())) {
                return true;
            }
        }
        return false;
    }
    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    bool search(string word) {
        if (words.find(word) == words.end()) {
            if (word.find(".") != string::npos && match(word, words)) {
                return true;
            }
            return false;
        }
        return true;
    }
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

当然可想而知,上面的代码超时了,所以人就不应该偷懒,即使set本身就是使用红黑树实现的,但是当包含.点算法明显退化了

首先我们看可以改进的地方,插入暂且不论,因为插入是为了搜索服务的,从搜索入手。
如果字典中包含:abc ab abde
而查询单词为: abe
如果使用第一种方式,我们话费的时间是 3 * 3 = 9 次比较,但是如果我们仔细观察,发现在9次比较中,前两个字符的比较就占用了2 * 3 = 6 次,占用了2/3的时间,而有效比较也就是e != c e != '' e!= d只有3次,那么我们可不可以将字典中出现的公共部分合并呢,这样我们查询时,只要查询一次,等到分叉的时候比较不同的即可,这样是不是就产生一种树形的结构了呢?

这种结构就叫做trie树

具体trie树的结构是什么样子的,大家可以随意百度一下,在数据结构中都有讲解,这里不在赘述,代码如下

/**
 *   Description: https://leetcode.com/problems/add-and-search-word-data-structure-design/
 *        Author: zhaoxiaohui
 *          Site: zhaoxiaohui.sinaapp.com
 *          Date: 2015-11-15
 */

struct TrieNode {
    TrieNode *children[26];
    string word;
    TrieNode() {
        memset(children, 0, sizeof(TrieNode *) * 26);
        word = "";
    }
};

class WordDictionary {
public:
    TrieNode *root;
    WordDictionary() {
        root = new TrieNode();
    }
    // Adds a word into the data structure.
    void addWord(string word) {
        const char *str = word.c_str();
        TrieNode *cur_node = root;
        while(*str) {
            if (cur_node->children[*str - 'a'] == NULL) {
                cur_node->children[*str - 'a'] = new TrieNode();
            }
            cur_node = cur_node->children[*str - 'a'];
            str++;
        }
        cur_node->word = word;
    }
    bool match(const char *str, int deep, int len, TrieNode *cur_node) {
        if (deep == len) {
            return !cur_node->word.empty();
        }
        if (*str != '.') {
            return cur_node->children[*str - 'a'] && match(str + 1, deep + 1, len, cur_node->children[*str - 'a']);
        } else {
            for (int i = 0; i < 26; i++) {
                if (cur_node->children[i] && match(str + 1, deep + 1, len, cur_node->children[i])) {
                    return true;
                }
            }
            return false;
        }
    }
    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    bool search(string word) {
        return match(word.c_str(), 0, word.length(), root);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值