LeetCode-字典树-Medium

记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步




208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)

map用来存放单词中的每一个字母
若为最后一个字母,加入标识 表示一个单词结束 方便搜索

class Trie(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root={}
        

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: None
        """
        node = self.root
        for w in word:
            if w in node.keys():
                node = node[w]
            else:
                node[w] = {}
                node = node[w]
        node['end'] = True
        

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self.root
        for w in word:
            if w in node.keys():
                node = node[w]
            else:
                return False
        
        if 'end' in node.keys():
            return True
        else:
            return False
        

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        node = self.root
        for w in prefix:
            if w in node.keys():
                node = node[w]
            else:
                return False
        return True

211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计

遇上题类似 在遇到"."的时候需要处理

class WordDictionary(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}
        

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: None
        """
        node = self.root
        for w in word:
            if w in node.keys():
                node = node[w]
            else:
                node[w] = {}
                node = node[w]
        node['end'] = {}
        

    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
        """
        def check(node,words):
            if not words:
                if ('end' in node.keys()):
                    return True
                else:
                    return False
            
            w = words[0]
            if w in node.keys():
                return check(node[w],words[1:])
            elif w=='.':
                for k in node.keys():
                    ret = check(node[k],words[1:])
                    if ret:
                        return True
            return False
            
        return check(self.root,word)

421. Maximum XOR of Two Numbers in an Array 数组中两个数的最大异或值

根据二进制从高位到低位建树
0往左,1往右
建完树后 依次遍历每一个数
数值某一位为0时在树上往右边1走
数值某一位为1时在树上往左边0走 这样两数异或可以得到1 如果不行则走唯一那条路
最后异或的到结果留下最大值

class TreeNode(object):
    def __init__(self,v):
        self.val = v
        self.left = None
        self.right = None

def findMaximumXOR(nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    root = TreeNode(-1)
    
    ##建树
    for num in nums:
        cur_node = root #当前的node
        for i in range(0, 32):               
            if num & (1 <<(31 - i)) == 0:    #当前位是0,放左边
                if not cur_node.left:
                    cur_node.left = TreeNode(0)
                cur_node = cur_node.left
            else:                            #当前位是1,放右边
                if not cur_node.right:
                    cur_node.right = TreeNode(0)
                cur_node = cur_node.right
        cur_node.left = TreeNode(num)        #在最后的左叶子节点记录一下这个数的值
                    
    res = 0
    ##遍历所有num 能够得到的最大值
    for num in nums:
        cur_node = root
        
        for i in range(0, 32):
            if num & (1 <<(31 - i)) == 0:     #当前位为0  尽量往右为1的地方走
                if cur_node.right:           
                    cur_node = cur_node.right
                else:                       
                    cur_node = cur_node.left
            else:                            #当前位为1  尽量往左为0的地方走
                if cur_node.left:            
                    cur_node = cur_node.left
                else:                        
                    cur_node = cur_node.right
        temp = cur_node.left.val             #得到这条路径存放的数的值
        
        res = max(res, num ^ temp)           #获取最大值
        
    print(res)
    return res

648. Replace Words 单词替换

1.将所有前缀建树 然后每个单词在树中检索 一旦检索到是dict中有的前缀 则替换成这个前缀
2.判断每个单词 遍历一遍dict 看这个单词是否以这个前缀开头 前缀事先按长度排序

def replaceWords(dict, sentence):
        """
        :type dict: List[str]
        :type sentence: str
        :rtype: str
        """
        node = {}
        
        def insert(word):
            tmpnode = node
            for w in word:
                if w in tmpnode.keys():
                     tmpnode = tmpnode[w]
                else:
                    tmpnode[w] = {}
                    tmpnode = tmpnode[w]
            tmpnode['end'] = True
            
            
        def search(word):
            tmpnode = node
            for i in range(len(word)):
                w = word[i]
                if w in tmpnode.keys():
                    tmpnode = tmpnode[w]
                    if 'end' in tmpnode.keys():
                        return word[:i+1]
                        
                else:
                    return word
            return word
            
        
        for word in dict:
            insert(word)
        
        words=sentence.split(" ")
            
        res = " ".join([search(x) for x in words])
        
        print(res)
        return res
    
def replaceWords2(dict, sentence):
        """
        :type dict: List[str]
        :type sentence: str
        :rtype: str
        """        
        words=sentence.split(" ")
        dict.sort(key=len)
        ret = []
        for w in words:
            res = w
            for i in dict:
                if w.startswith(i):
                    res = i
                    break
            ret.append(res)
        print(" ".join(ret))
            
        return ret

676. Implement Magic Dictionary 实现一个魔法字典

1.将单词按长度分别存储
如果没有相同长度的 必定无法转换
如果有相同长度 则和相同长度的单词比较是否相差一个字母
2.还可以用广义邻居 相差一个字母的为邻居 如果与自己的邻居是邻居的单词且不等于自己 可以通过改变一个字母实现

class MagicDictionary(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        from collections import defaultdict
        self.dic=defaultdict(list)
        

    def buildDict(self, dict):
        """
        Build a dictionary through a list of words
        :type dict: List[str]
        :rtype: None
        """
        for w in dict:
            num = len(w)
            self.dic[num].append(w)
            
        

    def search(self, word):
        """
        Returns if there is any word in the trie that equals to the given word after modifying exactly one character
        :type word: str
        :rtype: bool
        """
        num = len(word)
        if num not in self.dic.keys():
            return False
        
        for w in self.dic[num]:
            tag = 0
            for i in range(num):
                if w[i]!=word[i]:
                    tag+=1
            if tag==1:
                return True
        return False

677. Map Sum Pairs 键值映射

map中存放key-val映射关系 覆盖储存
得到前缀后 遍历所有key 如果前缀匹配 则将val累加

class MapSum(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        
        self.dic = {}
        

    def insert(self, key, val):
        """
        :type key: str
        :type val: int
        :rtype: None
        """
        self.dic[key]=val
        

    def sum(self, prefix):
        """
        :type prefix: str
        :rtype: int
        """
        ret = 0
        for k in self.dic.keys():
            if k.startswith(prefix):
               ret+=self.dic[k] 
        print(ret)
        return ret
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值