class TrieNode():
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.isEnd = False
self.rank = 0
self.data = ''
class AutocompleteSystem(object):
def __init__(self, sentences, times):
self.root = TrieNode()
for i, sentence in enumerate(sentences):
self.addRecord(sentence, times[i])
self.keyWords = ''
def addRecord(self, sentence, time):
node = self.root
for c in sentence:
node = node.children[c]
node.isEnd = True
node.rank -= time
node.data = sentence
def input(self, c):
res = []
if c != '#':
self.keyWords += c
res = self.search(self.keyWords)
else:
self.addRecord(self.keyWords, 1)
self.keyWords = ''
return res
def search(self, sentence):
node = self.root
for c in sentence:
node = node.children.get(c)
if not node:
return []
res = self.dfs(node)
return [data for rank, data in sorted(res)[:3]]
def dfs(self, node): # 找到该节点下的所有句子
res = []
if node:
if node.isEnd:
res.append([node.rank, node.data])
for child in node.children.values():
res.extend(self.dfs(child))
return res
class TrieNode():
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.isWord = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for c in word:
node = node.children[c]
node.isWord = True
def search(self, word):
node = self.root
for c in word:
node = node.children.get(c) # 不用用 node.children[c] 否则永远都不会是None
if not node:
return False
return node.isWord
def startsWith(self, prefix):
node = self.root
for c in prefix:
node = node.children.get(c)
if not node:
return False
return True
class TrieNode():
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.isWord = False
class WordDictionary(object):
def __init__(self):
"""
TrieNode:
根节点不包含字符,除根节点外每一个节点都只包含一个字符。
从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
每个节点的所有子节点包含的字符都不相同。
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
node = self.root
for c in word:
node = node.children[c]
node.isWord = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
node = self.root
self.res = False
self.dfs(node, word)
return self.res
def dfs(self, node, word):
if not word:
if node.isWord:
self.res = True
return
if word[0] == '.':
for n in node.children.values():
self.dfs(n, word[1:])
else:
n = node.children.get(word[0]) # 不能写 node.children[word[0]] 不然会返回默认类型
if not n:
return
self.dfs(n, word[1:])
Trie = lambda: collections.defaultdict(Trie)
class FileSystem(object):
def __init__(self):
self.fs = Trie()
self.fileinfo = collections.defaultdict(str)
def ls(self, path):
if path in self.fileinfo:
return path.split('/')[-1:]
cur = self.fs
for token in path.split('/'):
if token in cur:
cur = cur[token]
elif token:
return []
return sorted(cur.keys())
def mkdir(self, path):
cur = self.fs
for token in path.split('/'):
if token:
cur = cur[token]
def addContentToFile(self, filePath, content):
self.mkdir(filePath)
self.fileinfo[filePath] += content
def readContentFromFile(self, filePath):
return self.fileinfo[filePath]
class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
trie = {}
for w in words:
t = trie
for c in w:
if c not in t:
t[c] = {}
t = t[c]
t['#'] = '#'
self.res = set()
self.used = [[0] * len(board[0]) for _ in xrange(len(board))]
for i in xrange(len(board)):
for j in xrange(len(board[0])):
self.find(i, j, board, trie, "")
return list(self.res)
def find(self, i, j, board, trie, pre):
if '#' in trie:
self.res.add(pre)
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
return
if not self.used[i][j] and board[i][j] in trie:
self.used[i][j] = True
for x, y in ((-1, 0), (1, 0), (0, 1), (0, -1)):
self.find(i+x, j+y, board, trie[board[i][j]], pre+board[i][j])
self.used[i][j] = False