码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode211

时间:2020-04-04 09:48:52      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:def   nod   tree   判断   for   har   log   turn   +=   

 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),改造出来的。

leetcode211

标签:def   nod   tree   判断   for   har   log   turn   +=   

原文地址:https://www.cnblogs.com/asenyang/p/12630296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!