1 class TrieNode: 2 def __init__(self): 3 self.words = 0 4 self.edges = [None] * 26 5 6 7 class WordDictionary: 8 def __init__(self): 9 self.root = TrieNode() 10 11 def addWord(self, word: str) -> None: 12 self.insertHelper(self.root,word,0) 13 14 def search(self, word: str) -> bool: 15 return self.searchHelper(self.root,word,0) != 0 16 17 def insertHelper(self,node,word,pos): 18 if pos == len(word): 19 node.words += 1 20 else: 21 char_code = ord(word[pos]) - 97 22 if node.edges[char_code] == None: 23 node.edges[char_code] = TrieNode() 24 self.insertHelper(node.edges[char_code],word,pos+1) 25 26 27 def searchHelper(self,node,word,pos): 28 if pos == len(word): 29 return node.words 30 else: 31 if word[pos] == '.':#任意字符的判断 32 for i in range(26): 33 if node.edges[i] != None: 34 res = self.searchHelper(node.edges[i],word,pos+1) 35 if res != 0: 36 return res 37 return 0 38 else:#具体字母的判断 39 char_code = ord(word[pos]) - 97 40 if node.edges[char_code] == None: 41 return 0 42 else: 43 return self.searchHelper(node.edges[char_code],word,pos+1)
算法思路:前序树Trie。
根据 leetcode208 Implement Trie (Prefix Tree),改造出来的。