[LeetCode] 211. Design Add and Search Words Data Structure_Medium tag: Trie, DFS
作者:互联网
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary
class:
WordDictionary()
Initializes the object.void addWord(word)
Addsword
to the data structure, it can be matched later.bool search(word)
Returnstrue
if there is any string in the data structure that matchesword
orfalse
otherwise.word
may contain dots'.'
where dots can be matched with any letter.
Example:
Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output [null,null,null,null,false,true,true,true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord("bad"); wordDictionary.addWord("dad"); wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return False wordDictionary.search("bad"); // return True wordDictionary.search(".ad"); // return True wordDictionary.search("b.."); // return True
Constraints:
1 <= word.length <= 500
word
inaddWord
consists lower-case English letters.word
insearch
consist of'.'
or lower-case English letters.- At most
50000
calls will be made toaddWord
andsearch
.
Ideas:因为是word相关,所以考虑用trie来做,addWord就跟传统的Trie做的一样,不停往后加,直到最后那个node使node.isWord = True. 建立一个searchNode的helper function, 因为有‘.’, 可能需要从中间的node下去继续找, check first character, if matches, 继续找,否则return False, 如果是‘.’, 那么将所有的children都走一遍,然后recursive search (word[1:], child),如果有True,那么返回True,将所有child 都走遍没有True,最后返回False
Code:
class TrieNode: def __init__(self): self.isWord = False self.children = dict() class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord(self, word: str) -> None: node = self.root for c in word: if c not in node.children: node.children[c] = TrieNode() node = node.children[c] node.isWord = True def search(self, word: str) -> bool: return self.searchNode(word, self.root) def searchNode(self, word, node) -> bool: if not word: return node.isWord fir = word[0] if fir == '.': for child in node.children: if self.searchNode(word[1:], node.children[child]): return True return False elif fir in node.children: return self.searchNode(word[1:], node.children[fir]) return False # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word)
标签:node,Search,Medium,word,211,self,search,addWord,return 来源: https://www.cnblogs.com/Johnsonxiong/p/14952670.html