leetcode-5.22[*748. 最短完整词、653. 两数之和 IV - 输入 BST、821. 字符的最短距离](python实现)

题目1

在这里插入图片描述

题解1

class Solution:
    def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
        s = [w for w in licensePlate.lower() if ord(w)>=97 and ord(w)<=122]
        words.sort(key=lambda x:len(x))   #按单词长度进行排序
        for w in words: 
            w_copy=list(w)
            for i in s:             #判断单词是否包含牌照所有字母
                if i in w_copy:
                    w_copy.remove(i)
                else:                    #不满足条件
                    break
            else:
                return w                    #返回满足条件的单词

附上题目链接

题目2

在这里插入图片描述

题解2

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def findTarget(self, root: TreeNode, k: int) -> bool:
        num = self.getSortlist(root)
        l,r = 0, len(num)-1
        while l < r:
            if num[l] + num[r] < k:
                l += 1
            elif num[l] + num[r] > k:
                r -= 1
            else:
                return True
        return False


    def getSortlist(self, root):
        if root is None:
            return []
        return self.getSortlist(root.left) + [root.val] + self.getSortlist(root.right)

附上题目链接

题目3

在这里插入图片描述

题解3

class Solution:
    def shortestToChar(self, S: str, C: str) -> List[int]:
        """
            正向求每个字符距离C的距离
        """
        # 默认的prev无穷大
        prev = float('-inf')
        ans = []
        for i, x in enumerate(S):
            if x == C: prev = i
            ans.append(i - prev)

        """
            反向求每个字符距离C的距离
        """
        prev = float('inf') 
        for i in range(len(S) - 1, -1, -1):
            if S[i] == C: prev = i
            # 求出对应座标距离的最小值
            ans[i] = min(ans[i], prev - i)
        return ans

附上题目链接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章