leetcode刷题笔记-tire

复习时候做421

642. Design Search Autocomplete System

leetcode刷题笔记-tire_第1张图片

leetcode刷题笔记-tire_第2张图片

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
    

 

208. Implement Trie (Prefix Tree)

leetcode刷题笔记-tire_第3张图片

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

211. Add and Search Word - Data structure design

leetcode刷题笔记-tire_第4张图片

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:])
        

 

588. Design In-Memory File System

leetcode刷题笔记-tire_第5张图片

leetcode刷题笔记-tire_第6张图片

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]

212. Word Search II

leetcode刷题笔记-tire_第7张图片

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
            

 

你可能感兴趣的:(Algorithm)