211. Add and Search Word - Data structure design

Posted 咖啡中不塌缩的方糖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了211. Add and Search Word - Data structure design相关的知识,希望对你有一定的参考价值。

 

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

For example:

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

Note:
You may assume that all words are consist of lowercase letters a-z.

 

public class TrieNode {
    public TrieNode[] Child {get;set;}
    public bool EndWord {get;set;}
    // Initialize your data structure here.
    public TrieNode() {
        Child = new TrieNode[26];
        EndWord = false;
    }
}

public class WordDictionary {
    public TrieNode root  = new TrieNode();
    // Adds a word into the data structure.
    public void AddWord(String word) {
        var sentinel = root;
        foreach(char w in word)
        {
            if(sentinel.Child[w-a] == null) sentinel.Child[w-a] = new TrieNode();
            sentinel = sentinel.Child[w-a];
        }
        sentinel.EndWord = true;
        
    }

    // Returns if the word is in the data structure. A word could
    // contain the dot character ‘.‘ to represent any one letter.
    public bool Search(string word) {
        return Search(word,root,0);
    }
    
    public bool Search(string word, TrieNode t, int index)
    {
        if(index == word.Length) return t.EndWord;
        if(word[index] == .)
        {
            foreach(var c in t.Child)
            {
                if(c!= null && Search(word,c,index+1)) return true;
            }
            return false;
        }
        if(t== null ||t.Child[word[index]-a] == null) return false;
        return Search(word,t.Child[word[index]-a],index+1);
    }
}

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.AddWord("word");
// wordDictionary.Search("pattern");

 

以上是关于211. Add and Search Word - Data structure design的主要内容,如果未能解决你的问题,请参考以下文章

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design