[LeetCode]#821. Shortest Distance to a Character

Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
class Solution:
def shortestToChar(self, S, C):
index_nums=[]
for i, letter in enumerate(S):
if letter == C:
index_nums.append(i)
ans = []
l=len(S)
l2=len(index_nums)
d=[None]*l2
for j in range(l):
for k in range(l2):
d[k]=abs(j-index_nums[k])
ans.append(min(d))
return ans

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store