Dict & Trie

208. Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true
class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.d = {}
        self.end_of_word = '#'

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        node = self.d
        for char in word:
            node = node.setdefault(char,{})
        node[self.end_of_word] = self.end_of_word

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        node = self.d
        for char in word:
            if char not in node:
                return False
            node = node[char]
        return self.end_of_word in node
    
    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        node = self.d
        for char in prefix:
            if char not in node:
                return False
            node = node[char]
        return True


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
实现字典树

参数运行示范:

b={};node=b;for char in word:node = node.setdefault(char,{});print(node)

输出:{}{}{}{}{}

b  输出:{'a': {'p': {'p': {'l': {'e': {}}}}}}

node[end_of_word] = end_of_word;node

输出:{'#': '#'}

b  输出:{'a': {'p': {'p': {'l': {'e': {'#': '#'}}}}}}

'a' in node  输出:False

node = b;'a' in node;  输出:True

node=node['a'];node;  输出:{'p': {'p': {'l': {'e': {'#': '#'}}}}}

79. Word Search
board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        
        if not board:return False
        for i in range(len(board)):
            for j in range(len(board[i])):
                if self.helper(board,i,j,word):
                    return True
        return False
                    
    
    def helper(self,board,row,col,k):
        if len(k)==0:return True
        if row<0 or row>=len(board) or col<0 or col >=len(board[0]) or k[0]!=board[row][col]:
            return False
        tmp = board[row][col]
        board[row][col]='#'
        res = self.helper(board,row-1,col,k[1:]) or self.helper(board,row+1,col,k[1:]) 
        or self.helper(board,row,col-1,k[1:]) or self.helper(board,row,col+1,k[1:]) 
        board[row][col] = tmp
        return res
DFS
 
212. Word Search II
board = [
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
words = ["oath","pea","eat","rain"]

Output: ["eat","oath"]
import collections
dx = [-1,1,0,0]
dy = [0,0,-1,1]
END_OF_WORD = '#'

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        if not board or not board[0]: return []
        if not words: return []
        self.result = set()
        
        root = collections.defaultdict()
        for word in words:
            node = root
            for char in word:
                node = node.setdefault(char,collections.defaultdict())
            node[END_OF_WORD] = END_OF_WORD
            
        self.m, self.n = len(board),len(board[0])

        for i in range(self.m):
            for j in range(self.n):
                if board[i][j] in root:
                    self._dfs(board,i,j,"",root)
        return list(self.result)
                    
    def _dfs(self,board,i,j,cur_word,cur_dic):
        cur_word+=board[i][j]
        cur_dic = cur_dic[board[i][j]]
        
        if END_OF_WORD in cur_dic:
            self.result.add(cur_word)
            
        tmp,board[i][j] = board[i][j],'@'
        for k in range(4):
            x,y = i + dx[k], j+ dy[k]
            if 0 <= x <self.m and 0<= y < self.n
                and board[x][y] != '@' and board[x][y] in cur_dic:
                self._dfs(board,x,y,cur_word,cur_dic)
        board[i][j]=tmp
字典树+DFS
 
原文地址:https://www.cnblogs.com/ybxw/p/12918447.html