LeetCode 821. 字符的最短距离缩略图

给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。

返回一个整数数组 answer ,其中 answer.length == s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。

两个下标 i 和 j 之间的 距离 为 abs(i - j) ,其中 abs 是绝对值函数

821. 字符的最短距离 – 力扣(Leetcode)

LeetCode 821. 字符的最短距离插图
OpenCV步步精深-可心科创工作室

思路:

先统计c下标,然后遍历计算最短距离。

python3实现:

class Solution:
    def shortestToChar(self, s: str, c: str) -> List[int]:
        # 先统计所有c的下标
        c_idx_list = [elem_idx for elem_idx in range(len(s)) if s[elem_idx] == c]
        print("c_idx_list:", c_idx_list)

        # 依次比较
        result = []
        for each in range(len(s)):
           result.append(min([abs(every-each) for every in c_idx_list]))
        return result
LeetCode 821. 字符的最短距离插图1
OpenCV步步精深-可心科创工作室

更多干货见 OpenCV步步精深

作者 admin

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注