0131leetcode刷题5道python

211

题目描述:
请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 WordDictionary :
WordDictionary() 初始化词典对象
void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配
bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 false 。word 中可能包含一些 ‘.’ ,每个 . 都可以表示任何一个字母。

示例:
在这里插入图片描述
解答:

class WordDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        from collections import defaultdict
        self.lookup={
    
    }


    def addWord(self, word: str) -> None:
        tree=self.lookup
        for a in word:
            tree=tree.setdefault(a,{
    
    })
        tree["#"]={
    
    }

    def search(self, word: str) -> bool:
        def helper(word,tree):
            if not word:
                if "#" in tree:
                    return True
                return False
            if word[0]==".":
                for t in tree:
                    if helper(word[1:],tree[t]):
                        return True
            elif word[0] in tree:
                if helper(word[1:],tree[word[0]]):
                    return True
            return False
        return helper(word,self.lookup)




# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

648

题目描述:
在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。
现在,给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。
你需要输出替换之后的句子。

示例:
在这里插入图片描述
解答:

class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        rootset=set(dictionary) #将所有单词存入集合,去重,方便存取

        def replace(word):
            for i in range(1,len(word)):
                if word[:i] in rootset:
                    return word[:i]
            return word
        
        return " ".join(map(replace,sentence.split()))

778

题目描述:
在一个 N x N 的坐标方格 grid 中,每一个方格的值 grid[i][j] 表示在位置 (i,j) 的平台高度。
现在开始下雨了。当时间为 t 时,此时雨水导致水池中任意位置的水位为 t 。你可以从一个平台游向四周相邻的任意一个平台,但是前提是此时水位必须同时淹没这两个平台。假定你可以瞬间移动无限距离,也就是默认在方格内部游动是不耗时的。当然,在你游泳的时候你必须待在坐标方格里面。
你从坐标方格的左上平台 (0,0) 出发。最少耗时多久你才能到达坐标方格的右下平台 (N-1, N-1)?

示例:
在这里插入图片描述

解答:

class Solution:
    def swimInWater(self, grid: List[List[int]]) -> int:
        f={
    
    }
        def find(x):
            f.setdefault(x,x)
            while x!=f[x]:
                f[x]=f[f[x]]
                x=f[x]
            return x
        def union(x,y):
            f[find(x)]=find(y)
        
        rows,cols=len(grid),len(grid[0])
        edges=[]
        for i in range(rows):
            for j in range(cols):
                idx=i*cols+j
                if i: edges.append([idx,idx-cols,max(grid[i][j],grid[i-1][j])])
                if j: edges.append([idx,idx-1,max(grid[i][j],grid[i][j-1])])
        edges.sort(key=lambda x:x[2])
        
        ans=0
        for x,y,w in edges:
            if find(x)==find(y): continue
            union(x,y)
            ans=max(ans,w)
            if find(0)==find(rows*cols-1):break
        return ans

1631

题目描述:
你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。
一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。
请你返回从左上角走到右下角的最小 体力消耗值 。

示例:
在这里插入图片描述
解答:

class Solution:
    def minimumEffortPath(self, heights: List[List[int]]) -> int:
        #暴力破解
        que=deque([[0,0,0]])
        t=[[float('inf')]*len(i) for i in heights]
        t[0][0]=0
        while que:
            i,j,k=que.popleft()
            if k<=t[i][j]:
                for x,y in (i+1,j),(i-1,j),(i,j-1),(i,j+1):
                    if 0<=x<len(heights) and 0<=y<len(heights[0]):
                        z=max(k,abs(heights[x][y]-heights[i][j]))
                        if z<t[x][y]:
                            t[x][y]=z
                            que.append((x,y,z))
        return t[-1][-1]

面试题08.07

题目描述:
无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。

示例:
在这里插入图片描述

解答:

class Solution:
    def permutation(self, S: str) -> List[str]:
        #python自带排列组合方法
        from itertools import permutations
        result=[]
        for i in permutations(S,len(S)):
            result.append("".join(i))
        return result

猜你喜欢

转载自blog.csdn.net/yeqing1997/article/details/113364228
今日推荐