Lintcode 单词的添加与查找

 单词的添加与查找

设计一个包含下面两个操作的数据结构:addWord(word)search(word)

addWord(word)会在数据结构中添加一个单词。而search(word)则支持普通的单词查询或是只包含.a-z的简易正则表达式的查询。

一个 . 可以代表一个任何的字母。

 注意事项

你可以假设所有的单词都只包含小写字母 a-z。

样例
addWord("bad")
addWord("dad")
addWord("mad")
search("pad")  // return false
search("bad")  // return true
search(".ad")  // return true
search("b..")  // return true
AC代码如下:
struct trieNode {
        trieNode() : terminableSize(0) {
            for (int i = 0; i < 26; ++i) {
                children[i] = NULL;
            }
        }
        
        ~trieNode() {
            for (int i = 0; i < 26; ++i) {
                if (children[i]) {
                    delete children[i];
                    children[i] = NULL;
                }
            }
        }
        
        int terminableSize;
        trieNode *children[26];
};

class WordDictionary {
public:
    WordDictionary() : root(new trieNode) {}
    
    size_t Index(char c) {
        return static_cast<size_t>(c % 26);
    }
    
    // Adds a word into the data structure.
    void addWord(string word) {
        // Write your code here
        trieNode *cur = root;
        for (size_t i = 0; i < word.size(); ++i) {
            size_t idx = Index(word[i]);
            if (!cur->children[idx]) {
                cur->children[idx] = new trieNode;
            }
            cur = cur->children[idx];
        }
        ++cur->terminableSize;
    }

    // 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 search_dfs(word, root);
    }
    
    bool search_dfs(string word, trieNode *cur) {
        if (word.size() == 0 && cur->terminableSize > 0)
            return true;
        for (size_t i = 0; i < word.size(); ++i) {
            if (word[i] == '.') {
                for (size_t j = 0; j < 26; ++j) {
                    if (cur->children[j] && search_dfs(word.substr(i + 1), cur->children[j]))
                        return true;
                }
                return false;
            }
            else {
                size_t idx = Index(word[i]);
                if (!cur->children[idx])
                    return false;
                cur = cur->children[idx];
            }
        }
        if (cur->terminableSize > 0)
            return true;
        return false;
    }
    
private:
    
    trieNode *root;
};

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值