**Leetcode 211. Add and Search Word - Data structure design | Tries

https://leetcode.com/problems/add-and-search-word-data-structure-design/description/

写的不够熟练。。。


const int TK = 59, tb = 'A';

class WordDictionary {
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        tree.push_back( vector<int>(TK+1, 0) );
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        int rt = 0, i = 0, nxt;
        for ( ; i < word.size(); rt = nxt, i++) {
            nxt = tree[rt][ word[i] - tb ];
            if (0 == nxt) {
                tree[rt][word[i] - tb] = nxt = tree.size();
                tree.push_back( vector<int>(TK+1, 0) );
            }
        }
        // cout << "add rt:" << rt << endl;
        tree[rt][TK] = 1;
    }
    
    bool sear(string word) {
        int rt = 0, i = 0;
        for (; rt = tree[rt][word[i]- tb]; i++) {
            if (i == word.size() - 1) 
                return tree[rt][TK];
        }
        return 0;
    }
    
    /** 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) {
        // cout << "-->word:" << word << endl;
        return dfs(0, word);
    }
    
    
    bool dfs(int rt, string w) {
        // cout << "rt:" << rt << " w:" << w << " t:" << tree[rt][TK] << endl;
        if (w.size() == 0) {
            return tree[rt][TK];
        }

        bool ret = false;
        if (w[0] != '.') {
            if (tree[rt][w[0] - tb ] == 0) return 0;
            return dfs(tree[rt][w[0] - tb ], w.substr(1));
        } else {
            for (char c = 'a'; c <= 'z'; c++) {
                if (tree[rt][c - tb ] == 0) continue;
                ret |= dfs(tree[rt][c - tb], w.substr(1));
                if (ret) return ret;
            }
            for (char c = 'A'; c <= 'Z'; c++) {
                if (tree[rt][c - tb ] == 0) continue;
                ret |= dfs(tree[rt][c - tb], w.substr(1));
                if (ret) return ret;
            }
            return ret;
        }
    }
    
    
    vector< vector<int> > tree;
};

/**
 * 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、付费专栏及课程。

余额充值