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

数据结构:字典树
1.题目:
设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。

示例:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

2.代码:

#define MAXN 30

typedef struct WordDictionary{
    bool end;
    struct WordDictionary* next[MAXN];
}WordDictionary;

/** Initialize your data structure here. */
WordDictionary* wordDictionaryCreate() {
    WordDictionary* tree=(WordDictionary* )malloc(sizeof(WordDictionary)); 
    tree->end=false;
    for(int i=0;i<MAXN;i++)
        tree->next[i]=NULL;
    return tree;
}

/** Adds a word into the data structure. */
void wordDictionaryAddWord(WordDictionary* obj, char* word) {
    int i=0,k;
    while(word[i]){    
        k=word[i]-'a';
        if(!obj->next[k]){
            WordDictionary* temp=wordDictionaryCreate();
            obj->next[k]=temp;            
        }   
        obj=obj->next[k];                               
        i++;
    }
    obj->end=true;
}

//递归回溯
//主要思路:
//若index没有到strlen(word), 两种情况:
//1.word[index]=='.':递归回溯,一个一个试,若存在一个成了,返回true,否则返回false;
//2.word[index]!='.':直接比较下一个;
//注意点:比较的是obj->next[]里有没有word[index],当index==strlen(word)-1时,虽然是比较的最后一位,但是,此时obj还在树中倒数第二位位置。
//当index=strlen(word)时,此时虽然index已经超了,但是obj指的是字典树中该单词的最后一位,这时才知道有没有end;
//当然,若只是判断前缀的话,index==strlen(word)-1时已经可以返回了。

/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool find(WordDictionary* obj, char* word,int index){        
    if(obj){        
        if(index==strlen(word))      
            return obj->end;    
        if(word[index]=='.'){
            for(int i=0;i<MAXN;i++)    
                if(find(obj->next[i],word,index+1))
                    return true; 
            return false;
        }                    
        return find(obj->next[word[index]-'a'],word,index+1);                                   
    }
    return false;
}

bool wordDictionarySearch(WordDictionary* obj, char* word) {
    return find(obj,word,0);
}

void wordDictionaryFree(WordDictionary* obj) {
    if(!obj)
        return;
    for(int i=0;i<MAXN;i++){
        if(obj->next[i])
            wordDictionaryFree(obj->next[i]);
    }
    free(obj);
}

/**
 * Your WordDictionary struct will be instantiated and called as such:
 * struct WordDictionary* obj = wordDictionaryCreate();
 * wordDictionaryAddWord(obj, word);
 * bool param_2 = wordDictionarySearch(obj, word);
 * wordDictionaryFree(obj);
 */

3.知识点:

字典树+递归回溯;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值