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:

  1. S string length is in [1, 10000].
  2. is a single character, and guaranteed to be in string S.
  3. All letters in and C 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

            

                

            

            

        

 

posted on 2019-02-13 09:43  锋上磬音  阅读(93)  评论(0编辑  收藏  举报