[LeetCode]#821. Shortest Distance to a Character
Environment: Python 3.7
Key technique: enumerate
Given a string S
and a character C
, return an array of integers representing the shortest distance from the character C
in the string.
Example 1:
Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
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.
Analysis:
As below example, follow below steps.
- Find e in S location [3,5,6,11]
- We can calculate letter distance based on e location. For example, I is [3,5,6,11]
- Find minimum is 3.
- Therefore, the answer is [3,2,1,0,1,0,0,1,2,2,1,0]

Solution:
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
Submitted result:

Reference: