Created
July 23, 2018 08:01
-
-
Save luojiyin1987/40a51743f085af7eb4f980b86725d8eb to your computer and use it in GitHub Desktop.
Shortest Distance to a Character
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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