标签:
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
标签:
原文地址:http://www.cnblogs.com/renyualbert/p/5894660.html