LeetCode 821 Shortest Distance to a Character 解题报告
作者:互联网
题目要求
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
标签:Distance,string,index,res,Character,字符,字符串,821,character 来源: https://www.cnblogs.com/yao1996/p/10368211.html