首页 > 代码库 > 211. Add and Search Word - Data structure design
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") -> falsesearch("bad") -> truesearch(".ad") -> truesearch("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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。