LeetCode#211 Add and Search Word - Data structure design

1、本题与先前的Trie树相比,最大的差别就在引入了对通配符".“的处理。但由于引入此,就需要在出现”."的同一节点分支全部进行搜索,才能不漏掉所有可能。
2、搜索采用递归较好。

class WordDictionary {
private:
    struct TNode{
        char key;
        map<char, TNode*> node;
        int count;
        TNode(char letter):key(letter), count(0){}
    };
    TNode* rootPtr;
	//use last node and current string
	bool reccurrentSearch(TNode* lastPtr, string str){
		TNode* searchPtr = lastPtr;
		int strLen = str.length();
		if(!strLen && lastPtr->count){
			return true;
		}
		for(int i = 0; i < strLen; i++){
			char ch = str[i];
			if(ch == '.'){
				bool flag = 0;
				string remainWord;
				remainWord.assign(str.begin()+i+1, str.end());
				for(auto it:searchPtr->node){
					flag |= reccurrentSearch(it.second, remainWord);
					if(flag)
						return true;
				}
				if(!flag)
					return false;
			}else{
				auto it = searchPtr->node.find(ch);
				if(it == searchPtr->node.end()){
					return false;
				}
				searchPtr = it->second;
			}
		}
		if(searchPtr->count)
			return true;
		
		return false;
	}
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        rootPtr = new TNode(0);
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        TNode* innerPtr = rootPtr;
        for(auto ch:word){
            auto it = innerPtr->node.find(ch);
            if(it == innerPtr->node.end()){
                innerPtr->node[ch] = new TNode(ch);
                innerPtr = innerPtr->node[ch];
            }else{
                innerPtr = it->second;
            }
        }
		innerPtr->count++;
    }
    
    /** 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 reccurrentSearch(rootPtr, word);
    }
};

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

余额充值