Given a string S
and a character C
, return an array of integers representing the shortest distance from the character C
in the string.
Note:
S
string length is in [1, 10000].
C
is a single character, and guaranteed to be in string S
.S
and C
are lowercase. 题目给出一个字符串和一个字符,要求得到字符串中每一个字符和该字符的最短距离。可以先得到已知字符的所有索引,再遍历字符串得到每一个字符与该字符的最短距离。
class Solution:
def shortestToChar(self, S: ‘str‘, C: ‘str‘) -> ‘List[int]‘:
index = []
res = []
for i, v in enumerate(S):
if v == C:
index.append(i)
for i, v in enumerate(S):
res.append(min(list(map(lambda x:abs(x-i), index))))
return res
LeetCode 821 Shortest Distance to a Character 解题报告
原文:https://www.cnblogs.com/yao1996/p/10368211.html