Leetcode 211. 添加与搜索单词 - 数据结构设计

借用Trie树,addword就是insert,搜索的时候因为有’.’的存在,用递归dfs的思路

#define cti(x) (x-'a')
#define itc(x) (x+'a')
const int maxn = 70005;
const int sigma_size = 26;
class WordDictionary {
public:
    /** Initialize your data structure here. */
    int ch[maxn][sigma_size], val[maxn] = {}, sz;
    WordDictionary() {
        sz = 1, memset(ch[0], 0, sizeof(ch[0]));
    }

    /** Adds a word into the data structure. */
    void addWord(string word) {
        int o = 0;
        for (int i = 0; i < word.size(); ++i) {
            if (!ch[o][cti(word[i])])
                memset(ch[sz], 0, sizeof(ch[sz])), val[sz] = 0, ch[o][cti(word[i])] = sz++;
            o = ch[o][cti(word[i])];
        }
        val[o] = 1;
    }

    /** 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, int index, int o) {
        if (index == word.size()) return val[o];
        if (word[index] != '.') {
            if (ch[o][cti(word[index])])return search(word, index + 1, ch[o][cti(word[index])]);
            else return false;
        }
        for (int i = 0; i<sigma_size; ++i)
            if (ch[o][i] && search(word, index + 1, ch[o][i])) return true;
        return false;
    }
    bool search(string word) {
        return search(word, 0, 0);
    }
};

/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* bool param_2 = obj.search(word);
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值