821. 字符的最短距离

exiaohu 于 2022-04-19 发布

题目链接:821. 字符的最短距离

暴力计算。

from functools import reduce
from typing import List


class Solution:
    def shortestToChar(self, s: str, c: str) -> List[int]:
        words = s.split(c)

        def cal(j: int, w: str) -> List[int]:
            if j == 0:
                return [len(w) - i for i, _ in enumerate(w)]
            elif j == len(words) - 1:
                return [i + 1 for i, _ in enumerate(w)]
            else:
                return [min(len(w) - i, i + 1) for i, _ in enumerate(w)]

        return reduce(lambda x, y: x + [0] + y, [cal(j, w) for j, w in enumerate(words)])