Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save luojiyin1987/40a51743f085af7eb4f980b86725d8eb to your computer and use it in GitHub Desktop.
Save luojiyin1987/40a51743f085af7eb4f980b86725d8eb to your computer and use it in GitHub Desktop.
Shortest Distance to a Character
class Solution:
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
n = len(S)
result = [n for i in range (n)]
left, right = -n , 2*n
for i in range(n):
j = n -1 - i
if S[i] == C:
left = i
if S[j] == C:
right = j
result[i] = min(result[i], dist(i, left))
result[j] = min(result[j], dist(j, right))
return result
def dist(a,b):
if a -b >0 :
return a-b
else:
return b -a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment