Skip to content

Latest commit

 

History

History
58 lines (43 loc) · 2.04 KB

821-shortest-distance-to-a-character.md

File metadata and controls

58 lines (43 loc) · 2.04 KB

821. Shortest Distance to a Character - 字符的最短距离

给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。

示例 1:

输入: S = "loveleetcode", C = 'e'
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

说明:

  1. 字符串 S 的长度范围为 [1, 10000]
  2. C 是一个单字符,且保证是字符串 S 里的字符。
  3. S 和 C 中的所有字母均为小写字母。

题目标签:

题目链接:LeetCode / LeetCode中国

题解

这题比较简单,先记录C出现的位置,然后再次扫描S,计算与左侧C和右侧C的最小间隔,主要难点在于边界的处理。可以把一个很小和很大的数分别插入到C出现位置数组的两端,这样就可以不额外处理边界了,代码会优雅点。

Language Runtime Memory
python3 48 ms N/A
class Solution:
    def shortestToChar(self, S, C):
        """
        :type S: str
        :type C: str
        :rtype: List[int]
        """
        cps = [-1 * len(S)]
        cps.extend([i for i, s in enumerate(S) if s == C])
        cps.append(2 * len(S))
        p = 1
        res = []
        for i, s in enumerate(S):
            if i < cps[p]:
                res.append(min( i - cps[p-1] , cps[p] - i ))
            else:
                p += 1
                res.append(0)
        return res