题目要求
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 stringS
. - All letters in
S
andC
are lowercase.
题目分析及思路
题目给出一个字符串和一个字符,要求得到字符串中每一个字符和该字符的最短距离。可以先得到已知字符的所有索引,再遍历字符串得到每一个字符与该字符的最短距离。
python代码
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