给你一个字符串 s
和一个字符 c
,且 c
是 s
中出现过的字符。
返回一个整数数组 answer
,其中 answer.length == s.length
且 answer[i]
是 s
中从下标 i
到离它 最近 的字符 c
的 距离 。
两个下标 i
和 j
之间的 距离 为 abs(i - j)
,其中 abs
是绝对值函数

思路:
先统计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
