Shortest Distance to a Character
Input:
S = "loveleetcode", C = 'e'
Output:
[3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]S string length is in [1, 10000].
C is a single character, and guaranteed to be in string S.
All letters in S and C are lowercase.class Solution:
def shortestToChar(self, S: str, C: str) -> List[int]:
ll = len(S)
res = [ll]*ll
pos = -ll #注意此处取值弄成最大就好
for i in range(ll):
if S[i] == C:
pos = i
res[i] = 0
else:
res[i] = min(res[i],abs(pos - i))
for i in range(ll-1,-1,-1):
if S[i] == C:
pos = i
res[i] = 0
else:
res[i] = min(res[i],abs(pos - i))
return resLast updated