LeetCode 821 Shortest Distance to a Character (Python)

Posted by 小明MaxMing on February 7, 2021

题目

Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the shortest distance from s[i] to the character c in s.

解题思路

先找出每个c出现的位置,同时遍历字符串和c出现的位置,找到距离最近的c

代码

class Solution:
    def shortestToChar(self, s: str, c: str) -> List[int]:
        pos, res = [], []
        for i in range(len(s)):
            if s[i] == c:
                pos.append(i)
        p = 0
        for i in range(len(s)):
            if i < pos[0]:
                res.append(pos[0] - i)
            elif i > pos[-1]:
                res.append(i - pos[-1])
            elif i == pos[p]:
                res.append(0)
                p += 1
            else:
                res.append(min(pos[p] - i, i - pos[p - 1]))
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅