[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]
  1. S string length is in [1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. All letters in S and C are lowercase.
  1. Find e in S location [3,5,6,11]
  2. We can calculate letter distance based on e location. For example, I is [3,5,6,11]
  3. Find minimum is 3.
  4. Therefore, the answer is [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
Fatboy Slim

Fatboy Slim

Interesting in any computer science.